toxicate20
toxicate20

Reputation: 5410

Vector of maps of objects

I want to push an a map that contains an instance of a class to a vector. The following code is used

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

Could someone please explain to me why the push_back is failing? I could give you the errors thrown but they are way to too much for this case i think.

Upvotes: 0

Views: 1196

Answers (4)

fatihk
fatihk

Reputation: 7929

std::vector< std::map<std::string, Obj> > v; should be :

std::vector< std::pair<std::string, Obj> > v;

std::pair and std::map are different

Upvotes: 1

praks411
praks411

Reputation: 1992

You can try something like this

std::vector<std::map<std::string, Obj>> v;
std::map<std::string,Obj> v_map;
v_map.insert(std::pair(std::string("test"),Obj("testtype")));
v.push_back(v_map);

Upvotes: 1

taocp
taocp

Reputation: 23664

The problem is here:

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

According to std::mak_pair documentation

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

v expect that you push a std::map object into it, but you are pushing an object of std::pair. std::map and std::pair are two different things.

You may try:

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

Upvotes: 2

epatel
epatel

Reputation: 46051

Can this work?

int main (int argc, char ** argv)
{
 std::vector< std::map<std::string, Obj> > v;
 std::map<std::string, Obj> m;

 m["test"] = Obj("testtype");

 v.push_back(m);

 return 0;
}

Upvotes: 1

Related Questions