[英]Why does `std::for_each_n` not compile?
#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:使用 gcc 9.2.1 ( -std=c++17
),编译失败:
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看一眼for_each_n
告诉我它调用
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.但显然, for_each
返回一个函数对象与for_each_n
返回一个迭代器不兼容。
How do I use for_each_n
?我如何使用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
返回传入的函数对象的副本。
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).for_each_n
返回一个迭代器,它指向经过迭代的范围末尾之后的第一个元素v.begin() + 2
在本例中为v.begin() + 2
)。
These two types are not compatible, and having for_each_n
return the result of a for_each
loop should not compile.这两种类型不兼容,并且让for_each_n
返回for_each
循环的结果不应该编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.