【问题标题】:C++ Map with vector as key. How to make it so vector order doesn't matter?以向量为键的 C++ 映射。如何使其矢量顺序无关紧要?
【发布时间】:2020-04-19 12:10:40
【问题描述】:

我有一个将整数向量作为键的映射。我用值的关键向量 {1, 2, 3}

初始化地图
typedef std::map<std::vector<int>, std::string> VectorMap;
VectorMap vectorMap;
vectorMap[std::vector<int>{1, 2, 3}] = "test";

然后我使用count方法显示是否可以找到VectorMap中的条目,以{1, 2, 3}的向量为key。

std::cout << "count: " << vectorMap.count(std::vector<int>{1, 2, 3}) << std::endl;

这会返回正确的计数。

计数:1

但是我想这样做,所以向量中整数的顺序无关紧要。所以我尝试与上面相同,但将矢量内容翻转,即{3, 2, 1}

std::cout << "count: " << vectorMap.count(std::vector<int>{3, 2, 1}) << std::endl;

这将返回 0。

计数:0

我想让矢量比较与内容的顺序无关,只要内容相同即可。

{1, 2, 3} count: 1
{3, 2, 1} count: 1
{1, 2} count: 0
{1, 2, 3, 4} count : 0

我怎样才能做到这一点?我应该完全使用不同的容器而不是 std::vector 吗?

【问题讨论】:

    标签: c++ containers stdvector stdmap unordered


    【解决方案1】:

    如果键中元素的顺序无关紧要,那么您可能可以使用 std::set(如果所有元素都应该是唯一的)或 std::multiset,如果键可以有重复元素。 IE。 std::map&lt;std::set&lt;int&gt;, std::string&gt;.

    【讨论】:

      【解决方案2】:

      如果你想维护这些类型,你可以通过为你的映射定义一个自定义的无序比较器来做到这一点,如下所示:

      #include <vector>
      #include <map>
      #include <iostream>
      #include <algorithm>
      
      struct VectorComparatorOrderless
      {
          bool operator()(const std::vector<int>& a, const std::vector<int>& b)const // comparator a < b
          {
              if (a.size() < b.size()) return true;
              if (a.size() > b.size()) return false;
      
              return !std::all_of(a.cbegin(), a.cend(),
                  [&](const int& elementOfVectorA) -> bool
                  {
                      return std::find(b.cbegin(), b.cend(), elementOfVectorA) != b.cend();
                  }
              );
          }
      };
      
      typedef std::map<std::vector<int>, std::string, VectorComparatorOrderless> VectorMap;
      
      int main()
      {
      
          VectorMap vectorMap;
      
          vectorMap[std::vector<int>{1, 2, 3}] = "test";
      
          std::cout << "count: " << vectorMap.count(std::vector<int>{1, 2, 3}) << std::endl;
      
          std::cout << "count: " << vectorMap.count(std::vector<int>{3, 2, 1}) << std::endl;
      
          std::cout << "count: " << vectorMap.count(std::vector<int>{2, 3, 1}) << std::endl;
      
          std::cout << "count: " << vectorMap.count(std::vector<int>{2, 3}) << std::endl;
      
          std::cout << "count: " << vectorMap.count(std::vector<int>{2}) << std::endl;
      
          std::cout << "count: " << vectorMap.count(std::vector<int>{1,2,3,4}) << std::endl;
      
          std::cin.get();
      }
      

      输出:

      count: 1
      count: 1
      count: 1
      count: 0
      count: 0
      count: 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        相关资源
        最近更新 更多