map的key可以是数组吗?(映射数组错误)
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("%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
但这不是你想要的……数组与指针几乎相同,因此不能构建数组的映射。它只会在检索/设置指针的值时比较内存中的指针,而不会比较其内容。
相关文章:
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- 具有 2 个分量的数组的特征映射到 3 的向量
- 将数组的元素插入映射的时间复杂度是多少?
- 如何初始化字节数组的映射?
- 数组中未映射的内存访问从python传递到c++
- 当 map 是一个整数数组并且由 operator[] 创建时,它是否初始化其映射类型
- 如何为映射和priority_queue编写比较器,其中元素是二维数组
- 特征:将数组映射到矩阵大小未知的矩阵
- 一维数组映射方式的性能差异问题
- 如何在Windows上将BYTE数组映射为FILE *
- 将数组映射回现有特征矩阵
- 如何在将多维 int 数组映射到 C++ 中的字符串时实现在地图上查找或计数
- 从数组映射到整数在C++中无法正常工作
- 安全地将数组映射到类C++
- 将c++数组映射到特征矩阵
- 将二维数组映射到Eigen::Matrix
- 将2D数组映射到CUDA中的RGB到GreyScale程序中的块网格
- 在c++中存储数组映射
- 使用可变模板和类型列表将不透明数组映射到函数参数
- 2D 数组映射与 if 语句 C++