1

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 ?

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
   // .....
});
1
  • 2
    std::for_each will pass an object from the container, not iterator. You should use explicit cycle that uses iterators. Make a function (probably template) from it. Commented Feb 26, 2014 at 19:33

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I like STL Alg style.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.