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

Cha*_*son 2 c++ dictionary stl vector c++11

我有以下内容:

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

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

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

101*_*010 5

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

std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};
                                                    ^             ^    ^             ^
Run Code Online (Sandbox Code Playgroud)

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


Aur*_*iga 5

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

std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};
Run Code Online (Sandbox Code Playgroud)

是查德说的。