[...] based on the 1st element of the pair< int , int> and if those are equal then sort them according to their second elements [...]
std::pair
already has lexicographical comparison C++03 20.2.2/6:
template <class T1, class T2>
bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y);
Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second)
So, as WhozCraig pointed out, you should just compare .second
s of outer pair.
This is a lambda expression, I dont have C++ 11 with me, is there no other way possible?
Use functor:
struct LessSecond
{
template<typename T, typename U>
bool operator()(const std::pair<T,U> &x, const std::pair<T,U> &y) const
{
return x.second < y.second;
}
};
// ...
sort(x.begin(), x.end(), LessSecond());
Or maybe more generic version (depends on your needs):
struct LessSecondGeneric
{
template<typename Pair>
bool operator()(const Pair &x, const Pair &y) const
{
return x.second < y.second;
}
};
LIVE DEMO:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
struct LessSecond
{
template<typename T, typename U>
bool operator()(const std::pair<T,U> &x, const std::pair<T,U> &y) const
{
return x.second < y.second;
}
};
int main()
{
using namespace std;
vector<pair<string , pair<int, int>>> x
{
{"1", {2, 1}}, {"2", {1, 1}}, {"3", {1, 2}}
};
sort(x.begin(), x.end(), LessSecond());
for(const auto &p : x)
cout << p.first << " (" << p.second.first << ", " << p.second.second << ")" << endl;
}
Output is:
2 (1, 1)
3 (1, 2)
1 (2, 1)