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

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

当我尝试编译时,出现以下错误:

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/

相关文章:

linux - 在 linux 上使用 mingw 交叉编译 c++11 线程

Python 按值降序对嵌套字典进行排序

python - 选择字典键 :values randomly

c++ - 使用纳秒与 boost :posix_time

C++,为大数据传递最佳参数和返回类型

C++11 移动语义和右值引用

c++ - 无法在 gnu linux c++ 中写入 ostream 错误 : invalid operands of types ofstream and ‘const char [2]’ to binary ‘operator

c++ - 从控制台坐标点 - Visual C++ 2010 Express Edition

c++ - 使用类的二叉搜索树

c# - 找不到类型或命名空间 "SafeIntDictionary"