Cra*_*aig 2 c++ iteration predicate unique-ptr c++11
我有一个std::unique_ptr<Foo>对象矢量.我想获得符合某些条件的所有矢量项的集合.我看到std函数,但它们似乎都测试谓词(并返回bool)或返回单个元素.
是否有内置机制来获取作为向量子集的集合?如果没有,有没有办法构建一个迭代器来测试项目对任意谓词(以识别符合我的条件的那些)和一种机制来返回满足该谓词的所有项目?
请注意,因为你有一个unique_ptr的向量,那些元素只能被移动,即一旦你有了子集,原始向量将不再相同.
最不具破坏性的方法是使用std::stable_partition将向量分成两组,同时将所有内容保存在同一向量中:
auto sep = std::stable_partition(vec.begin(), vec.end(), [](const auto& foo) {
return foo->is_good();
});
// the part `vec.begin() .. sep` contains all "good" foos.
// the part `sep .. vec.end()` contains all "bad" foos.
Run Code Online (Sandbox Code Playgroud)
如果顺序并不重要,使用std::partition代替.用法是一样的.
如果要将坏foos拆分为另一个向量,可以使用std::copy_if+ std::make_move_iterator将对象移出.请注意,这将在任何地方留下漏洞.用它std::remove来清理它们.
decltype(vec) bad_vec;
std::copy_if(std::make_move_iterator(vec.begin()),
std::make_move_iterator(vec.end()),
std::back_inserter(bad_vec),
[](const auto& p) { return !p->is_good(); });
auto new_end = std::remove(vec.begin(), vec.end(), nullptr);
vec.erase(new_end, vec.end());
Run Code Online (Sandbox Code Playgroud)
如果您不再关心"坏"对象,请使用std::remove_if:
auto new_end = std::remove_if(vec.begin(), vec.end(), [](const auto& foo) {
return !foo->is_good();
});
vec.erase(new_end, vec.end());
// now `vec` only contains "good" foos.
Run Code Online (Sandbox Code Playgroud)
如果你只想获得原始指针,而不是unique_ptr本身,你可以std::transform用来填充a vector<Foo*>然后remove_if过滤它......但是在这一点上,编写for循环可能更容易.
std::vector<int*> good_vec;
for (const auto& foo : vec) {
if (foo->is_good()) {
good_vec.push_back(foo.get());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
337 次 |
| 最近记录: |