c++ - 如何使用 STL 将结构 vector 转换为映射

标签 c++ vector stl 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;
};

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

我在编写类似 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)));

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

最佳答案

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

更简洁...

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

关于c++ - 如何使用 STL 将结构 vector 转换为映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29170675/

相关文章:

c++带有缩进的自定义输出流

c++ - 将 void* 作为 std::unordered_map 的第二个模板参数是什么意思?

c++ - Valarray 和自定义分配器

c++ - C/C++ 下划线 t/type (_t/_type) 和类名?

c++ - 使用构造函数更改 vector 类型?

c++ - unistd read() 不起作用

c++ - const 指针的 vector ?

c++ - 拓扑排序

c++ - 如何阻止发送到 PuTTY 的字符破坏其标题/输出?

c++ - 为什么我不能在 const 参数函数/方法中传递 const 对象?