无法填充C数组的映射

C++ Unable to populate a map of C arrays

本文关键字:映射 数组 填充      更新时间:2023-10-16
typedef std::map<std::string,int> string2intMap;
typedef string2intMap arrOfMaps[3] ;
//map : string --> array of maps of <std::string,int>
std::map<std::string,arrOfMaps> tryingStuff;
//map : string --> int
string2intMap s;
s["key"]= 100;
tryingStuff["hello"][0] = s;

上面的代码不能编译,问题行是:tryingStuff["hello"][0] = s;

下面是编译器的提示:

c:program files (x86)microsoft visual studio 10.0vcincludemap(215): error C2440: '<function-style-cast>' : cannot convert from 'int' to 'std::map<_Kty,_Ty> [3]'
2>          with
2>          [
2>              _Kty=std::string,
2>              _Ty=int
2>          ]
2>          There are no conversions to array types, although there are conversions to references or pointers to arrays
2>          c:program files (x86)microsoft visual studio 10.0vcincludemap(210) : while compiling class template member function 'std::map<_Kty,_Ty> (&std::map<_Kty,arrOfMaps>::operator [](const std::basic_string<_Elem,_Traits,_Ax> &))[3]'
2>          with
2>          [
2>              _Kty=std::string,
2>              _Ty=int,
2>              _Elem=char,
2>              _Traits=std::char_traits<char>,
2>              _Ax=std::allocator<char>
2>          ]
2>          c:worktoottootcodetootimtoolsdoobimdoobim.cpp(95) : see reference to class template instantiation 'std::map<_Kty,_Ty>' being compiled
2>          with
2>          [
2>              _Kty=std::string,
2>              _Ty=arrOfMaps
2>          ]
2>
2>Build FAILED.
2>
2>Time Elapsed 00:00:01.38
========== Build: 1 succeeded, 1 failed, 5 up-to-date, 0 skipped ==========

你知道怎么让它工作吗??我不想改变数据结构,它是

不能将c风格的数组存储在容器中,因为它们不能赋值;你不能这样做:

int x[3] = { 0, 1, 2 };
int y[3] = { 3, 4, 5 };
x = y;

但是容器需要能够赋值/复制它们所存储的元素。

考虑使用std::vectorboost::array *来代替原始的C数组。


*这可以在c++标准的最新版本中找到std::array

基本上数组是不可复制的。
你想使用的是一个向量…

typedef std::map<std::string,int>  string2intMap;
typedef std::vector<string2intMap> arrOfMaps;
//map : string --> array of maps of <std::string,int>
std::map<std::string,arrOfMaps>    tryingStuff;
//map : string --> int
string2intMap s;
s["key"]= 100;
tryingStuff["hello"].push_back(s);