如何根据值的属性对地图进行排序? [英] How can I sort a map according to a property of its values?

查看:144
本文介绍了如何根据值的属性对地图进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个具有如下向量的地图:

  map< int,vector< int> mymap; 

如何根据 n 的值。

键而不是。如果您需要容器的元素以某个特定的值定义的顺序存在,那么您使用的容器不正确。



您可以切换到 set ,并利用key和value之间没有区别的事实,并自己破解底层排序:

  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);
}
};

/ **
*一组(int,int {2,})对,由
*中的第2个元素排序,每个对的第2项。
* /
std :: set< std :: pair< int,std :: vector< int>>,MyComparator< 1> my_data;

int main()
{
my_data.insert(std :: make_pair(1,std :: vector< int> {0,5,0,0})) ;
my_data.insert(std :: make_pair(2,std :: vector< int> {0,2,0,0}));
my_data.insert(std :: make_pair(3,std :: vector< int> {0,1,0,0}));
my_data.insert(std :: make_pair(4,std :: vector< int> {0,9,0,0}));

for(const auto& el:my_data)
std :: cout< el.first<< '';
}

//输出:3 2 1 4



现场演示



但是,如果您仍然需要对键执行查找,那么您真的遇到了麻烦,需要重新思考一些事情。您可能需要复制数据或提供索引向量。


I've created a map having a vector as below:

map<int,vector<int>> mymap;

How can I sort this map according to the nth value of the vector contained by map?

解决方案

You can't. You can provide a custom comparator to make the underlying data get sorted another way than the default, but this only relates to keys, not values. If you have a requirement for your container's elements to exist in some specific, value-defined order, then you're using the wrong container.

You can switch to a set, and take advantage of the fact that there is no distinction there between "key" and "value", and hack the underlying sorting yourself:

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::set<std::pair<int, std::vector<int>>, MyComparator<1>> my_data;

int main()
{
    my_data.insert(std::make_pair(1, std::vector<int>{0,5,0,0}));
    my_data.insert(std::make_pair(2, std::vector<int>{0,2,0,0}));
    my_data.insert(std::make_pair(3, std::vector<int>{0,1,0,0}));
    my_data.insert(std::make_pair(4, std::vector<int>{0,9,0,0}));

    for (const auto& el : my_data)
        std::cout << el.first << ' ';
}

// Output: 3 2 1 4

(live demo)

However, if you still need to perform lookup on key as well, then you're really in trouble and need to rethink some things. You may need to duplicate your data or provide an indexing vector.

这篇关于如何根据值的属性对地图进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆