-3

Doesn't an iterator have to be deferenced before using? I can't understand why

for_each(vecResult.begin(), vecResult.end(), [](auto counter) {cout << counter << endl;
});

is working (showing the contents of the vector) but

for_each(vecResult.begin(), vecResult.end(), [](auto counter) {cout << *counter << endl; });

is not.(My visual studio shows an error message

"'<<':illegal for class)
Spinkoo
  • 2,080
  • 1
  • 7
  • 23
John
  • 1

1 Answers1

2

A possible implementation of std::for_each is as follows:

template<class InputIt, class UnaryFunction>
constexpr UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
    for (; first != last; ++first) {
        f(*first);
    }
    return f; // implicit move since C++11
}

source: https://en.cppreference.com/w/cpp/algorithm/for_each

As you can see above, what is passed to the f (in your case, the lambda) is already dereferenced. So, in your example counter is not an iterator, it's the value to which the iterator points.

frogatto
  • 28,539
  • 11
  • 83
  • 129