Reputation: 115
i need to know how can we sort a vector of user define class using its elements. Say i have a class called "coordinates" with getX and getY method that return an int value. I have created and array of vector "vector PointTwoD vcP2D(5);"
class coordinates {
int getX();
int getY();
)
Now the issue, 1) I need to sort the vector "vcP2D" using getX() and sort in asc order 2) Say an user enters the "2" as the x coordinate. And using that info i need to find which vector contains 2
Please advice
Upvotes: 0
Views: 393
Reputation: 76785
This will do:
std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d){ return c.getX() < d.getX(); });
It uses a C++11 Lambda expression as a binary predicate for std::sort
.
A short demonstration:
#include <algorithm>
#include <vector>
#include <iostream>
struct coordinates
{
int x;
int y;
};
int main()
{
std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} };
std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.x < d.x; });
std::cout << "sorted by x values, values of \"x\": " << v[0].x << " " << v[1].x << " " << v[2].x << "\n";
std::sort(v.begin(), v.end(), [](const coordinates& c, const coordinates& d) { return c.y < d.y; });
std::cout << "sorted by y values, values of \"x\": " << v[0].x << " " << v[1].x << " " << v[2].x << "\n";
}
A demo of how to find an element in the same way:
#include <algorithm>
#include <vector>
#include <iostream>
struct coordinates
{
int x;
int y;
};
int main()
{
std::vector<coordinates> v{ {2,3}, {0,0}, {1,5} };
auto result = std::find_if(v.begin(), v.end(), [](const coordinates& c){ return c.x == 1 && c.y == 5; });
if(result != v.end())
std::cout << "point (1,5) is number " << std::distance(v.begin(), result)+1 << " in the vector.\n";
else
std::cout << "point (1,5) not found.\n";
}
If you are looking to search in the sorted vector, you can use std::binary_search
which takes a comparison function (the same as std::sort
above). It also does not give an iterator to that element, only a true
or false
.
Upvotes: 6
Reputation: 154035
You need to define a strict weak order on your elements, either using operator< ()
or a binary predicate, and then use std::sort()
.
The easiest approach is to create a less than operator<()
:
bool operator< (coordinates const& c0, coordinates const& c1) {
// return a suitable result of comparing c0 and c1 such that operator<()
// become a strict weak order
}
With this all you need to do to sort a std::vector<coordinates>
is to use std::sort()
. To locate a specific object you would use std::lower_bound()
.
Upvotes: 3