#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v{ 1, 2, 3, 4 };
std::for_each_n(v.begin(), 2, [](int n) { });
}
With gcc 9.2.1 (-std=c++17
), this fails to compile:
error: could not convert 'std::for_each<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, main()::<lambda(int)> >(__first, __first.__gnu_cxx::__normal_iterator<int*, std::vector<int> >::operator+(__n2), (__f, main()::<lambda(int)>()))' from 'main()::<lambda(int)>' to '__gnu_cxx::__normal_iterator<int*, std::vector<int> >'
3900 | return std::for_each(__first, __first + __n2, __f);
A peek inside for_each_n
tells me that it calls
std::for_each(v.begin(), v.begin() + 2, ...)
But apparently, for_each
returning a function object is not compatible with for_each_n
returning an iterator.
How do I use for_each_n
?
This is a problem with the library implementation.
for_each
returns a copy of the function object that was passed in.
for_each_n
returns an iterator to the first element past the end of the range that was iterated over (v.begin() + 2
in this example).
These two types are not compatible, and having for_each_n
return the result of a for_each
loop should not compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With