Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `std::for_each_n` not compile?

Tags:

c++

c++17

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

like image 715
curiousguy12 Avatar asked Mar 09 '20 22:03

curiousguy12


Video Answer


1 Answers

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.

like image 120
1201ProgramAlarm Avatar answered Oct 18 '22 22:10

1201ProgramAlarm