使用STL查找向量中的所有元素 [英] using STL to find all elements in a vector
问题描述
我有一个元素集合,我需要操作,调用成员函数上的集合:
I have a collection of elements that I need to operate over, calling member functions on the collection:
std::vector<MyType> v;
... // vector is populated
-forward:
std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc));
如果要调用的函数有一个参数,也可以这样做。
A similar thing can be done if there's one argument to the function I wish to call.
我的问题是,如果它满足一些条件,我想在向量中的元素上调用一个函数。 std :: find_if
返回一个迭代器到满足谓词条件的第一个元素。
My problem is that I want to call a function on elements in the vector if it meets some condition. std::find_if
returns an iterator to the first element meeting the conditions of the predicate.
std::vector<MyType>::iterator it =
std::find_if(v.begin(), v.end(), MyPred());
我希望找到符合谓词的所有元素并对它们进行操作。
I wish to find all elements meeting the predicate and operate over them.
我一直在寻找 find_all
或 do_if
等价,或者我可以用现有的STL(这样我只需要迭代一次),而不是滚动我自己或简单做一个标准的迭代使用for循环和比较。
I've been looking at the STL algorithms for a "find_all
" or "do_if
" equivalent, or a way I can do this with the existing STL (such that I only need to iterate once), rather than rolling my own or simply do a standard iteration using a for loop and comparisons.
推荐答案
Boost Lambda让这很容易。
Boost Lambda makes this easy.
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/if.hpp>
std::for_each( v.begin(), v.end(),
if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ]
);
如果它很简单,你甚至可以省略定义MyPred这是lambda真正发光的地方。例如,如果MyPred意思是可被2整除:
You could even do away with defining MyPred(), if it is simple. This is where lambda really shines. E.g., if MyPred meant "is divisible by 2":
std::for_each( v.begin(), v.end(),
if_( _1 % 2 == 0 )[ std::mem_fun( &MyType::myfunc ) ]
);
更新:
使用C ++ 0x lambda语法也是非常好的(继续使用谓词模2):
Update: Doing this with the C++0x lambda syntax is also very nice (continuing with the predicate as modulo 2):
std::for_each( v.begin(), v.end(),
[](MyType& mt ) mutable
{
if( mt % 2 == 0)
{
mt.myfunc();
}
} );
乍一看,这看起来像是从boost :: lambda语法向后退一步,因为更复杂的函子逻辑很容易实现与c ++ 0x语法...其中任何非常复杂的boost :: lambda很快就很棘手。 Microsoft Visual Studio 2010 beta 2目前实现此功能。
At first glance this looks like a step backwards from boost::lambda syntax, however, it is better because more complex functor logic is trivial to implement with c++0x syntax... where anything very complicated in boost::lambda gets tricky quickly. Microsoft Visual Studio 2010 beta 2 currently implements this functionality.
这篇关于使用STL查找向量中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!