c++ - 如何根据其值的属性对 map 进行排序?

标签 c++ vector dictionary

我创建了一个具有如下 vector 的 map :

map<int,vector<int>> mymap;

如何根据 map 包含的 vector 的 nth 值对这个 map 进行排序?

最佳答案

你不能。你可以提供一个自定义比较器来使底层数据以不同于默认的方式排序,但这只与有关,而不是< em>值(value)观。如果您要求容器的元素以某种特定的、值定义的顺序存在,那么您就使用了错误的容器。

你可以切换到一个set,并利用“键”和“值”之间没有区别的事实,然后自己破解底层排序:

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 )

但是,如果您还需要对键执行查找以及,那么您就真的有麻烦了,需要重新考虑一些事情。您可能需要复制数据或提供索引 vector 。

关于c++ - 如何根据其值的属性对 map 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24241285/

相关文章:

python - 在 Python 3 中以恒定时间从字典中选择随机值?

c++ - 您可以在 C++ header 中包含 .cu 扩展 header 吗?

c++ - SQLite - 另存为?

c++ - 如何让 child 进入n路树?

C++ vector 和 push_back

c++ - vector 的对象如何访问 vector 元素

c++ - 在派生构造函数初始化列表中初始化模板

c++ - 从 vector 末尾指向类变量的指针

python - 将字典列表转换为 DataFrame 时出现类型错误

c++ - 创建 VARIANT 的 CMap 的正确方法