如何初始化一个包含std::map项的std::vector?

4

我有以下内容:

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

注:该错误是由于在初始化 vector 对象时没有正确提供参数类型所致。


4
将std::map视为std::pair的列表,可以尝试这样做:{ { {"close", 14.4} }, { {"close", 15.6} } }。这是一个包含两个map的向量,每个map中有一个pair。 - Chad
2
@Chad 答案应该放在答案框中,而不是作为评论。 - Barry
@Barry 完整的答案应该放在答案框中。我不想写一个好的答案,所以我写了一个评论。 - Chad
@Chad 如果你不想写答案,那就不要写。不要采取这种介于两者之间的半步,因为你实际上回答了问题,但只是在错误的地方。 - Barry
@Barry 我不同意,像“你试过了吗”这样的评论是有价值的,我将继续这样做。 - Chad
2个回答

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 元素的初始化。

5
使用三个大括号而不是两个。
std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};

他说的就是这个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接