繁体   English   中英

如何初始化std :: map项的std :: vector?

[英]How can I initialize an std::vector of std::map items?

我有以下内容:

#include <vector>
#include <map>
#include <string>

int main() {
    std::vector<std::map<std::string, double>> data = {{"close", 14.4}, {"close", 15.6}};

    return 0;
}

当我尝试编译时,我收到以下错误:

g ++ -std = c ++ 11 -Wall -pedantic ./test.cpp

./test.cpp:6:49:错误:没有用于初始化'std :: vector>'的匹配构造函数(又名'vector,allocator>,double >>')std :: vector> data = {{“close” ,14.4},{“close”,15.6}};

每个元素/对需要一对额外的大括号:

std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};
                                                    ^             ^    ^             ^

需要额外的大括号,因为std::map元素的类型是std::pair<const key_type, value_type>在你的情况下是std::pair<const std::string, double> 因此,您需要一对额外的大括号来向编译器表明std::pair元素的初始化。

使用3个括号而不是2个。

std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};

这是什么乍得说的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM