2011-12-28 25 views
0
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 [ 「你好」] [0] = S;C++無法填充地圖一個C數組

這裏是編譯器喊道:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\map(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.0\vc\include\map(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:\work\toot\tootcode\tootim\tools\doobim\doobim.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 ========== 

不知道如何使它發揮作用? (我不想改變這個數據結構,它是一個 map:string - >地圖數組)

+0

[性病::數組的矢量(可能重複http://stackoverflow.com/questions/8557579/stdvector-of-an- array) – 2011-12-28 16:36:06

回答

5

你不能將C風格的數組存儲在容器中,因爲它們是不可分配的;你不能這樣做:

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

x = y; 

但容器需要能夠分配/複製他們正在存儲的元素。

考慮使用std::vectorboost::array*而不是原始C數組。


*在C++標準的更新版本中可以找到std::array

+0

或者如果你有TR1,'std :: array'。 – ssube 2011-12-28 16:29:26

0

基本上陣列是不可複製的。
要使用是一個矢量什麼...

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