C++ 如何初始化std::map项的std::vector?
我有以下资料:C++ 如何初始化std::map项的std::vector?,c++,c++11,dictionary,vector,stl,C++,C++11,Dictionary,Vector,Stl,我有以下资料: #include <vector> #include <map> #include <string> int main() { std::vector<std::map<std::string, double>> data = {{"close", 14.4}, {"close", 15.6}}; return 0; } #包括 #包括 #包括 int main(){ 向量数据={{“关闭”,14.
#include <vector>
#include <map>
#include <string>
int main() {
std::vector<std::map<std::string, double>> data = {{"close", 14.4}, {"close", 15.6}};
return 0;
}
#包括
#包括
#包括
int main(){
向量数据={{“关闭”,14.4},{“关闭”,15.6};
返回0;
}
当我尝试编译时,我得到以下错误:
g++-std=c++11-Wall-pedantic./test.cpp
./test.cpp:6:49:错误:“std::vector>的初始化没有匹配的构造函数”(aka)
'向量,分配器>,双>>')
std::vector>data={{“close”,14.4},{“close”,15.6}
每个元素/对都需要一对额外的大括号:
std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};
^ ^ ^ ^
std::vector data={{{“close”,14.4},{{“close”,15.6}};
^ ^ ^ ^
由于
std::map
元素的类型为std::pair
,因此需要额外的一对大括号。因此,您需要一对额外的大括号来向编译器表示std::pair
元素的初始化 使用3个大括号而不是2个大括号
std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};
std::vector data={{{“close”,14.4},{{“close”,15.6}};
chad就是这么说的。试着把std::map想象成std::pairs的列表,试试这个:
{{{{“close”,14.4},{{“close”,15.6}}
。一个由2个地图组成的向量,每个地图有1对。@Chad答案属于答案框,而不是注释。@Barry将答案完全充实到答案框中。我不想写一个好的答案,所以我写了一条评论。@Chad如果你不想写答案,就不要写。不要在你真正回答问题的地方走这半步,而只是在错误的地方。@Barry我不同意,像“你试过了吗”这样的评论是有价值的,我会继续这样做。