我正在尝试使用char[]
作为map
的键:
#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;
}
但是抛出一个错误:
错误:数组用作初始值设定项
second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2((...(
即使这样也行不通:m["abcdefghi"]=4;
如何使用char []
作为密钥?我有几个关于SO的问题,但它们没有多大帮助。
注意:我用过string
但我想尝试char[]
只是出于好奇
数组既没有复制构造函数,也没有复制赋值运算符。数组没有默认的运算符<。
使用标准容器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;
}
使用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::string_view
:
#include <iostream>
#include <map>
#include <string_view>
int
main()
{
std::map<std::string_view, int> m;
char c[10] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
m[{c, sizeof(c)}] = 78;
}