[英]How can I sort a vector according to a property of its values?
If I have a vector of pairs 如果我有一对向量
vector<pair<int,vector<int>>> myvector;
How can I sort this vector according to nth element of its inner vector? 如何根据其内部向量的第n个元素对该向量排序?
My previously-asked question on this topic contains the answer of sorting a vector of pairs according to a second element of the pair by using a pre-defined sorting_function() as below. 我先前在该主题上提出的问题包含使用以下预定义的sorting_function()根据对的第二个元素对对向量进行排序的答案。 However, in this case, I have no idea what the form of sorting_function() should be... 但是,在这种情况下,我不知道sorting_function()的形式应为...
sort(v.begin(), v.end(), sorting_function());
You may re-use the comparator from my answer to your previous question; 您可以根据我对上一个问题的回答重新使用比较器; sort
expects an instance of it, so pass in a temporary one: sort
需要一个实例 ,因此传入一个临时实例 :
std::sort(v.begin(), v.end(), MyComparator<1>());
So, here's the full example: 因此,这是完整的示例:
template <std::size_t N>
struct MyComparator
{
typedef std::pair<int, std::vector<int>> value_type;
bool operator()(const value_type& lhs, const value_type& rhs)
{
return lhs.second.at(N) < rhs.second.at(N);
}
};
/**
* A set of (int, int{2,}) pairs, sorted by the 2nd element in
* the 2nd item of each pair.
*/
std::vector<std::pair<int, std::vector<int>>> my_data;
int main()
{
my_data.push_back(std::make_pair(1, std::vector<int>{0,5,0,0}));
my_data.push_back(std::make_pair(2, std::vector<int>{0,2,0,0}));
my_data.push_back(std::make_pair(3, std::vector<int>{0,1,0,0}));
my_data.push_back(std::make_pair(4, std::vector<int>{0,9,0,0}));
std::sort(my_data.begin(), my_data.end(), MyComparator<1>());
for (const auto& el : my_data)
std::cout << el.first << ' ';
}
// Output: 3 2 1 4
struct comparator
{
comparator (int n) : n(n) { }
typedef std::pair<int, std::vector<int>> key_type;
bool operator() (key_type const & k1, key_type const & k2)
{
return k1.second[n] < k2.second[n];
}
int n;
};
I have no idea where you want 'n' to come from, but basicly that's it. 我不知道您想从哪里来,但是基本上就是这样。 Also you should put bounds checking in it. 另外,您还应该在其中检查范围。
Then you can sort your array this way: 然后,您可以通过以下方式对数组进行排序:
std::sort(v.begin(), v.end(), comparator(n));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.