以矢量为键的 C++ 映射。如何使矢量顺序无关紧要?

C++ Map with vector as key. How to make it so vector order doesn't matter?

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

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

然后我用count的方法来显示是否可以用{1, 2, 3}的vector作为key找到VectorMap中的entry

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

这 returns 正确计数。

count: 1

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

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

这 returns 计数为 0。

count : 0

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

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

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

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

如果你想维护这些类型,你可以通过为你的映射定义一个自定义的无序比较器来实现,就像这样:

#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