[...] 쌍의 첫번째 요소를 기반으로 < INT, INT>
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)
: 그 같으면 다음
std::pair
이미 사전 식 비교 C++ 03 20.2.2/6을 가진다 [...] 두 번째 요소에 따라 그들을 정렬
WhozCraig이 지적했듯이, 바깥 쪽 쌍의 .second
을 비교해야합니다.
이것은 람다 식으로, 나는 C++ 11을 가지고 있지 않다. 가능한 다른 방법은 없을까?
사용 펑터 :
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());
아니면 더 일반적인 버전 (필요에 따라) :
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;
}
출력은 다음과 같습니다
2 (1, 1)
3 (1, 2)
1 (2, 1)
그것은 일했다 : D, 그런 중대한 대답을위한 blastfurnace에게 감사하십시오 : D, 너에게 일반적으로 그런 일을 달성하는 방법을 설명 할 수 있는다? 어떤 이론은 유용 할 것입니다 :) – AnkitSablok
[C++ 03 로컬 클래스는 템플릿 인수로 사용할 수 없습니다] (http://stackoverflow.com/a/5751990/1762344). –
@EvgenyPanasyuk : 고마워, 내가 엄격하게 C++ 03 컴파일러를 사용한 이후로 꽤 오래되었습니다. – Blastfurnace