c++ - 对象映射的 vector

标签 c++ dictionary vector

我想将包含类实例的映射推送到 vector 。使用了以下代码

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

class Obj {
 public:
  Obj() {}
  Obj(std::string type) : type(type) {}
  std::string type;
  std::string value;
};

int main (int argc, char ** argv)
{
 std::vector< std::map<std::string, Obj> > v;
 v.push_back(std::make_pair("test", Obj("testtype")));

 return 0;
}

有人可以向我解释为什么 push_back 失败了吗?我可以给你抛出的错误,但我认为对于这种情况来说它们太多了。

最佳答案

问题出在这里:

 std::make_pair("test", Obj("testtype");

根据 std::mak_pair documentation

std::make_pair
Creates a std::pair object, deducing the target type from the types of arguments.

v 期望您将 std::map 对象压入其中,但您压入的是 std::pair 对象。 std::mapstd::pair 是两个不同的东西。

你可以试试:

 std::map<std::string, Obj> mymap;
 mymap["test"] = Obj("testtype");
 v.push_back(mymap);

关于c++ - 对象映射的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16792900/

相关文章:

c++ - 在 vector 循环 C++ 中使用对象方法

c++ - 将 std::find_if() 与采用多个输入参数的比较函数一起使用

c++ - opencv 3.0.0 c++ detectMultiScale 检测到大量的人脸

android - 在 Android 上为 OpenCV 设置相机场景模式

c++ - 为什么在使用 std::remove() 从 vector 中删除多个值时会发生跳过?

python - 对于列表的列表,将字典与 collections.defaultdict 合并

c++ - C# 到 C++ 的转换 : Searching Arrays

c++ - 如何只执行一次代码?

python - 电子表格数据的最有效实现

python - 类型错误 : unhashable type: 'list' for webscraping project