如何使用STL将struct的向量转换为map

ToB*_*oBe 1 c++ stl vector c++03

我有一个std::vector<Person> v

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;
};
Run Code Online (Sandbox Code Playgroud)

我需要转变为 std::map<std::string,int> persons

在编写类似这样的代码时我遇到了困难:

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)));
Run Code Online (Sandbox Code Playgroud)

在c ++ 03中使用stl算法转换vector<Person> v成最佳方法是什么map<std::string,int> persons

Nim*_*Nim 7

IMO,一个简单的for循环在这里更加清晰..

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

你不可能认为bind你需要的混乱比上面更清楚..

在C++ 11中,这变成了

for (auto const& p : v)
  persons.emplace(p.GetName(), p.GetAge());
Run Code Online (Sandbox Code Playgroud)

更简洁......

基本上,使用算法很好,但不要仅仅为了使用它们而使用它们.