map的key可以是数组吗?(映射数组错误)

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

本文关键字:数组 映射 错误 map key      更新时间:2023-10-16

我想做一个映射,其中有数组的形式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("%dn",mapa[v]);
}

但是我得到一个错误,是因为数组不能是映射吗?

我想你实际上是指映射键类型。不,原始数组不能用作键,因为没有为它们声明内部的less操作符。

在这种情况下我能做什么?如果我用向量而不是数组,它会工作吗?

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

std::less()如何与std::array一起工作的确切文档可以在这里找到。

或者你可以像@NathanOliver指出的那样提供你自己的比较算法。


这是建议吗?

#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;

这里当然没有自动转换

这将编译为:

map<int *,int> mapa
但这不是你想要的……数组与指针几乎相同,因此不能构建数组的映射。它只会在检索/设置指针的值时比较内存中的指针,而不会比较其内容。