한 가지 방법은 사용자 정의 비교기를 std :: sort의 선택적 세 번째 인수로 사용하는 것입니다. Sort_pred라는이 사용자 지정 비교기는 다음과 같이 정의됩니다.
bool operator () (const std :: pair & lt; int, int & gt; left, left, const std :: pair & lt; int, int & gt; & amp; 오른쪽) {
왼쪽 반환 & lt; 오른쪽.
}
};
이 비교기를 사용하려면이 비교기를 사용하려면 std :: sort로 전달합니다.
C 11 Lambdas
C 11 컴파일러를 사용하는 경우 커스텀 비교 대신에 Lambdas를 활용하십시오 : std :: sort (v.begin (), v.end (), [] (const std :: pair & lt; int & gt; & amp; left, const std :: pair & lt; int, int & gt; 왼쪽 반환 & lt; 오른쪽. });
쌍 정렬을위한 일반 템플릿을 사용하여
struct sort_pred { bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) { return left.second < right.second; } };
struct sort_pred { bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) { return left.second < right.second; } };
는 더 큰 유연성과 재사용을 위해 sort_pair_second라는 일반 템플릿을 만들 수 있습니다.
템플릿. & lt; 클래스 T1, 클래스 T2, 클래스 프레드 = std :: Less & lt; t2 & gt; & gt; struct sort_pair_second { bool operator () (const std :: pair & lt; t1, t2 & gt; left, const std :: pair & lt; t1, t2 & gt; & amp; 오른쪽) { Pred P; 반환 p (왼쪽, 초, 오른쪽); } };
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) { return left.second < right.second; });
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3