有一个“vector 的 vector ” 看起来像这样
3 1 2 0 77
0 3 1 2 44
1 0 3 2 29
3 0 1 2 49
我想根据每一行的最后一个元素对它们进行排序,以便最后看起来像这样
1 0 3 2 29
0 3 1 2 44
3 0 1 2 49
3 1 2 0 77
当然,我的真实示例要复杂得多...但这基本上是我需要完成的。 现在我使用这个片段,它似乎是根据第一个元素排序的。
vector<vector<int>>population;
partial_sort( population.begin(),population.begin()+10, population.end() );
最佳答案
您可以使用 std::sort具有为 vector 提供严格弱排序的函数(或仿函数对象)。 IE。你定义了一个 vector-less-than 函数来正确地排序两个 vector ,就像这样(在我的脑海中)。 编辑:在评论之后,添加了对一两个空 vector 的检查,这确实让事情变得更棘手。
bool CustomVectorCompare(const std::vector<int> &i_lhs, const std::vector<int> &i_rhs)
{
if(i_rhs.empty())
return false; // If right side is empty, left can only be equal or larger
if(i_lhs.empty())
return true; // Consider an empty vector to be "smaller"
// than any non-empty vector.
return i_lhs.back() < i_rhs.back();
}
std::sort(population.begin(), population.end(), CustomVectorCompare);
关于c++ - 按最后一个元素对 vector 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1437816/