问题
vector<pair<int,int> > v;
for(i=0;i<5;i++){
cin>>b>>c;
v.push_back(make_pair(b,c));
}
sort(v.begin(),v.end());
Is it possible to write a comparator for the sort function such that v[i].first
is sorted in increasing order and for similar values of v[i].first
, v[i].second
is sorted in decreasing order?
like:-
i/p:
13 10
44 15
13 15
13 99
6 45
o/p:
6 45
13 99
13 15
13 10
44 15
回答1:
Sure, it's easy enough.
All you need to do is write a function with this signature:
bool f(std::pair<int, int> lhs, std::pair<int, int> rhs);
The function should return true
if and only if lhs < rhs
So, by your criteria, lhs
is smaller than rhs
if:
lhs.first < rhs.first
,- or
lhs.first == rhs.first && lhs.second > rhs.second
So, basically just put those together, and you get:
bool mycomparer(std::pair<int, int> lhs, std::pair<int, int> rhs) {
if (lhs.first < rhs.first) {
return true;
}
else if (lhs.first == rhs.first && lhs.second > rhs.second) {
return true;
}
else {
return false;
}
}
This could be written much more compactly, but I wanted to keep it simple and readable to get the point across. :)
回答2:
Here is a compact comparison function object that does what you want: (uses C++11 features)
struct Shivam {
typedef std::pair<int, int> const& param_type;
bool operator()(param_type lhs, param_type rhs) const {
return std::tie(lhs.first, rhs.second) < std::tie(rhs.first, lhs.second);
};
};
And use it like this:
std::sort(std::begin(v), std::end(v), Shivam{});
来源:https://stackoverflow.com/questions/24229200/comparator-for-vectorpairint-int