过滤STL容器的现代方法? [英] Modern way to filter STL container?

查看:77
本文介绍了过滤STL容器的现代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用了C#多年之后,我又回到C ++了,我想知道现代的-C ++ 11-过滤数组的方式,即,我们如何实现类似于此Linq查询的内容:

Coming back to C++ after years of C# I was wondering what the modern - read: C++11 - way of filtering an array would be, i.e. how can we achieve something similar to this Linq query:

var filteredElements = elements.Where(elm => elm.filterProperty == true);

为了过滤元素向量(字符串出于这个问题)

In order to filter a vector of elements (strings for the sake of this question)?

我真诚地希望使用旧的STL样式算法(甚至是扩展类,例如 boost :: filter_iterator

I sincerely hope the old STL style algorithms (or even extensions like boost::filter_iterator) requiring explicit methods to be defined are superseded by now?

推荐答案

请参阅 code>),现在需要定义显式方法?来自cplusplus.com中的 std :: copy_if

See the example from cplusplus.com for std::copy_if:

std::vector<int> foo = {25,15,5,-5,-15};
std::vector<int> bar;

// copy only positive numbers:
std::copy_if (foo.begin(), foo.end(), std::back_inserter(bar), [](int i){return i>=0;} );

std :: copy_if 计算lambda表达式对于此处的 foo 中的每个元素,如果返回 true ,则将值复制到 bar

std::copy_if evaluates the lambda expression for every element in foo here and if it returns true it copies the value to bar.

std :: back_inserter 允许我们在末尾实际插入新元素 bar (使用 push_back())的迭代器,而不必先将其调整为所需的大小。

The std::back_inserter allows us to actually insert new elements at the end of bar (using push_back()) with an iterator without having to resize it to the required size first.

这篇关于过滤STL容器的现代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆