我有以下内容:
#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: error: no matching constructor for initialization of 'std::vector >' (aka '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
的初始化。元素。
关于c++ - 如何初始化 std::map 项的 std::vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36507923/