[英]STL Algorithms using iterator in the target function
I want to use an function that requires the parameter to be an Iterator, is possible to apply it with an STL algoritm like std::for_each ? 我想使用要求参数为Iterator的函数,是否可以将其与std :: for_each之类的STL算法一起应用?
std::vector<int> v({0,1,2,3,4});
std::for_each(v.begin(), v.end(), [](std::vector<int>::iterator it)
{
// Do something that require using the iterator
// .....
});
You could easily make your own "implementation" that passes an iterator to the function. 您可以轻松地进行将迭代器传递给函数的自己的“实现”。
namespace custom {
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function fn)
{
while (first!=last) {
fn (first);
++first;
}
return fn;
}
}
std::vector<int> v({0,1,2,3,4});
custom::for_each(v.begin(), v.end(),
[](std::vector<int>::iterator it)
{
std::cout << *it << std::endl;
});
I don't see the advantage of this over a simple loop: 与简单的循环相比,我没有看到它的优点:
for (auto it = v.begin(); it != v.end(); ++it)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.