C++ 使用字符数组作为映射中的键
我试图使用C++ 使用字符数组作为映射中的键,c++,arrays,dictionary,stl,C++,Arrays,Dictionary,Stl,我试图使用char[]作为映射的键: #include<iostream> #include<map> #include<string> #include<utility> #include<list> using namespace std; int main(void) { map<char[10],int> m; char c[10]={'1','2','3','4','5','6','7','8
char[]
作为映射的键
:
#include<iostream>
#include<map>
#include<string>
#include<utility>
#include<list>
using namespace std;
int main(void)
{
map<char[10],int> m;
char c[10]={'1','2','3','4','5','6','7','8','9','0'};
m[c]=78;
return 0;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
内部主(空)
{
地图m;
字符c[10]={'1','2','3','4','5','6','7','8','9','0'};
m[c]=78;
返回0;
}
但这是一个错误:
错误:数组用作初始值设定项
第二个(std::forward(std::get(_tuple2))…)
即使这样也不行:m[“abcdefghi”]=4代码>
如何使用char[]
作为键?我有几个问题要问,但没什么帮助
注意:我使用了string
,但我想尝试char[]
只是出于好奇使用std::array
:
#include <array>
#include <iostream>
#include <map>
int
main()
{
using key_type = std::array<char, 10>;
std::map<key_type, int> m;
key_type c{ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
m[c] = 78;
}
数组既没有复制构造函数也没有复制赋值运算符。对于数组,没有默认运算符<
不要使用数组,而是使用标准容器std::array
比如说
#include<iostream>
#include <array>
#include<map>
int main()
{
std::map< std::array<char, 10>, int> m;
std::array<char, 10> c = {'1','2','3','4','5','6','7','8','9','0'};
m[c]=78;
return 0;
}
#包括
#包括
#包括
int main()
{
std::mapm;
数组c={'1','2','3','4','5','6','7','8','9','0'};
m[c]=78;
返回0;
}
我认为你是绝对正确的,严格的弱排序(@AgrudgeAmicus)这部分不是大问题。你可以提供一个比较器来解决:模板struct less{using type=typename std::remove\u extent\u t;static constexpr size\u t extent=std::extent\u v;constepr bool operator()(const type(&a)[extent],const type(&b)[extent])const{return std::lexicographic_compare(std::begin(a),std::end(a),std::begin(b),std::end(b));};
#include<iostream>
#include <array>
#include<map>
int main()
{
std::map< std::array<char, 10>, int> m;
std::array<char, 10> c = {'1','2','3','4','5','6','7','8','9','0'};
m[c]=78;
return 0;
}