Why does `std::for_each_n` not compile?

curiousguy12 :
#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 ?

1201ProgramAlarm :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368918&siteId=1