我想将包含类实例的映射推送到 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::map
和 std::pair
是两个不同的东西。
你可以试试:
std::map<std::string, Obj> mymap;
mymap["test"] = Obj("testtype");
v.push_back(mymap);
关于c++ - 对象映射的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16792900/