I have the following vector
with pair values:
first 3 second 2
first 1 second 2
first 1 second 1
first 2 second 2
I would like to sort my vector such that the result would be
==========================
first 1 second 2
first 1 second 1
first 2 second 2
first 3 second 2
That means:
- sort with respect to the first element.
- in case of equality sort with respect to the second element
My code looks like:
#include <utility> // std::pair
#include <iostream> // std::cout
#include <vector>
typedef std::pair<double, double> my_pair;
struct sort_pred
{
bool operator () (const my_pair& left, const my_pair& right)
{
return (left.first < right.first) && (left.second > right.second);
}
};
int main () {
std::vector<my_pair> data;
data.push_back(my_pair(3,2) );
data.push_back(my_pair(1,2) );
data.push_back(my_pair(1,1) );
data.push_back(my_pair(2,2) );
for(auto a: data)
std::cout << "first "<< a.first << " second " << a.second << std::endl;
std::cout << "==========================\n";
std::sort(data.begin(), data.end(), sort_pred());
for(auto a: data)
std::cout << "first "<< a.first << " second " << a.second << std::endl;
return 0;
}
The condition in the sort_pred
expressed what I would like to do, but is not correct. I get wrong values.
Any idea how this can be easily solved?