如何使用STL将结构的矢量转换为映射
How to transform a vector of struct into a map using STL
我有一个带的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)));
相关文章:
- 如何在 perl 中将多维映射从 c++ 转换为哈希
- 将C++映射转换为 Java 映射
- 类型映射资源并将列表转换为矢量(并返回)
- 将多映射转换为空指针,然后转换回多映射
- 如何在没有映射的情况下在枚举和字符串之间进行转换?
- 标准::映射转换器模板
- 将引用对具有shared_ptr作为值的映射转换为对具有shared_ptr const 作为值的映射的引用
- 在映射最小值和最大值时从未签名转换为已签名的最佳方法?
- 在将平截头体从摄影机空间转换为灯光空间以进行阴影映射方面存在主要问题
- 将 JNI -> jobject(基本上是 java 文件中的映射和/或映射的映射)转换为 std::map(c++)
- 将C++映射转换为python字典
- 如何使用STL将结构的矢量转换为映射
- 转换/映射迭代器<A>到迭代器<B>
- 将多映射迭代器转换为随机访问迭代器
- 将 STL 映射转换为结构
- Qt DBus 属性转换为映射
- 将多重映射值从 int 转换为字符串
- 指向成员函数的指针映射:无法将 void (*) 转换为 void (对象::*)
- 转换c++映射到C数组-性能
- 转换/映射方法最佳做法