cbu*_*art 1 c++ copy stl-algorithm
我想知道是否可以使用std::back_inserter从更复杂的结构中创建仅包含单个元素的向量。例如,在以下代码中:
struct Person {
std::string first_name;
std::string last_name;
int id;
};
std::vector<Person> people;
// Populate 'people'...
// Extract last names into single vector
std::vector<std::string> last_names;
std::copy(begin(people), end(people), std::back_inserter(last_names)); // <... ?
Run Code Online (Sandbox Code Playgroud)
到目前为止,我发现的唯一解决方案是创建一个强制转换运算符Person -> std::string:
struct Person {
// ...
operator std::string() const { return last_name; }
};
Run Code Online (Sandbox Code Playgroud)
但是,如果我想将first_name和提取last_name到两个向量中,这不是一个好的解决方案,更不用说晦涩难懂的隐式转换了。
有什么方法可以指示std::back_inserter如何构造要插入的元素?任何其他方式来创建这样的向量?显然,我不是指原始方式:
std::vector<std::string> last_names;
last_names.reserve(people.size());
for (const auto& person : people) {
last_names.push_back(person.last_name);
}
Run Code Online (Sandbox Code Playgroud)
但对于一些<algorithm>类似的人 ;)
我更喜欢仅使用 C++ 的答案,但如果需要,我愿意接受 Boost 解决方案。
您应该std::transform改为使用一元运算函数对象来对每个元素执行转换。例如
std::transform(std::begin(people),
std::end(people),
std::back_inserter(last_names),
[](const Person& person) { return person.last_name; }
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77 次 |
| 最近记录: |