私はこのタイプのベクトルを持っています: vector< pair<float, int> > vect;
float 値 (ペアの最初の値) の降順に従ってその要素を並べ替えたいです。たとえばvect = [<8.6, 4>, <5.2, 9>, <7.1, 23>]
、ソートした後[<5.2, 9>, <7.1, 23>, <8.6, 4>]
、C++ でそれを簡単に行うにはどうすればよいですか?
3678 次
2 に答える
4
std::vector<std::pair<float, int>> vect =
{
std::make_pair(8.6, 4),
std::make_pair(5.2, 9),
std::make_pair(7.1, 23)
};
std::sort(vect.begin(), vect.end(), [](const std::pair<float, int>& first, const std::pair<float, int>& second)
{
return first.first < second.first;
});
for (const auto& p : vect)
{
std::cout << p.first << " " << p.second << std::endl;
}
C++11.
http://liveworkspace.org/code/5f14daa5c183f1ef4e349ea26854f1b0
于 2012-07-26T09:12:09.753 に答える
4
struct cmp_by_first {
template<typename T>
bool operator<(const T& x, const T& y) const { return x.first < y.first; }
};
std::sort(vect.begin(), vect.end(), cmp_by_first());
于 2012-07-26T09:10:48.137 に答える