ToBe
ToBe

Reputation: 971

How to transform a vector of struct into a map using STL

I have a std::vector<Person> v with

struct Person
{
    Person(int i,std::string n) {Age=i; this->name=n;};
    int GetAge() { return this->Age; };
    std::string GetName() { return this->name; };
    private:
    int Age;
    std::string name;
};

and I need to transform to std::map<std::string,int> persons

I got stuck when coding something like this :

std::transform(v.begin(),v.end(),
  std::inserter(persons,persons.end()), 
  std::make_pair<std::string,int>(boost::bind(&Person::GetName,_1)),  (boost::bind(&Person::GetAge,_1)));

What is the best way to transform the vector<Person> v into map<std::string,int> persons by using stl algorithm in c++03?

Upvotes: 1

Views: 1228

Answers (2)

Nim
Nim

Reputation: 33655

IMO, a simple for loop is a lot clearer here..

for (vector<Person>::iterator i = v.begin(); i != v.end(); ++i)
  persons.insert(make_pair(i->GetName(), i->GetAge()));

You can't possibly argue that the bind mess you'll need is clearer than the above..

And in C++11, this becomes

for (auto const& p : v)
  persons.emplace(p.GetName(), p.GetAge());

Even more concise...

Basically, it's nice to use algorithms, but don't use them just for the sake of using them..

Upvotes: 7

ecatmur
ecatmur

Reputation: 157374

You just need to bind std::make_pair as well:

  std::transform(v.begin(), v.end(),
    std::inserter(persons, persons.end()),
    boost::bind(std::make_pair<std::string, int>,
      boost::bind(&Person::GetName, _1),
      boost::bind(&Person::GetAge, _1)));

Upvotes: 3

Related Questions