地图的键可以是数组吗? (映射数组错误)

Is it possible for the Keys of a map to be arrays? (Map array error)

我想制作一个以 int[27] 形式的数组作为键的地图,所以我尝试了以下操作:

#include <map>
using namespace std;
map<int[27] ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

但是我得到一个错误,是因为数组不能用作地图的键类型吗?
在这种情况下我能做什么?如果我使用向量而不是数组,它会起作用吗?


这是建议吗?

#include <cstdio>
#include <map>
using namespace std;
map<array<int,27> ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

这是有效的版本:

#include <cstdio>
#include <map>
#include <array>
using namespace std;
map<array<int,27>, int> mapa;
array<int,27> v;
int main(){
    mapa[v]++;
    printf("%d\n",mapa[v]);
}

这将编译:

map<int *,int> mapa

但这不是你想要的... 数组几乎与指针相同,因此您无法构建数组映射。当 retrieving/setting 它的值而不是它的内容时,它只会比较内存中的指针。

But I get an error, is it because arrays can't be a map?

我认为您实际上是指 映射键类型。不,原始数组不能用作键,因为没有为它们声明内在的 less 运算符。

What can I do in this case? Would it work if I used a vector instead of an array?

是的,您可以使用 std::vector<int> 作为密钥。更好的是 std::array<int,27>,如果你知道它是 27 的固定大小。

std::less() 如何与 std::array 一起工作的确切文档可以在 here.

中找到

或者,您可以提供自己的比较算法,正如@NathanOliver 所指出的那样。


Is this the suggestion?

#include <cstdio>
#include <map>
using namespace std;
map<array<int,27> ,int> mapa;
int n[27];
int main(){
    mapa[n]++;
}

差不多。你需要

std::array<int,27> n;

当然有,没有自动转换。