如何使用STL将结构的矢量转换为映射

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

本文关键字:转换 映射 何使用 STL 结构      更新时间:2023-10-16

我有一个带的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;
};

我需要转换为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)));

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

IMO,这里的简单for循环要清晰得多。。

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

你不能争辩说你需要的bind混乱比上面更清楚。。

在C++11中,这就变成了

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

更简洁。。。

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

您只需要绑定std::make_pair即可:

  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)));