c++ - 为什么 `std::for_each_n` 不能编译?

标签 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) { });
}

使用 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);

一窥内幕 for_each_n告诉我它叫
std::for_each(v.begin(), v.begin() + 2, ...)
但显然,for_each返回函数对象与 for_each_n 不兼容返回一个迭代器。

我如何使用 for_each_n ?

最佳答案

这是库实现的问题。

for_each 返回传入的函数对象的拷贝。

for_each_n 返回一个迭代器,指向经过迭代的范围末尾的第一个元素(在本例中为 v.begin() + 2)。

这两种类型不兼容,并且有 for_each_n返回 for_each 的结果循环不应该编译。

关于c++ - 为什么 `std::for_each_n` 不能编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60609400/

相关文章:

c++ - g++ 对 std::filesystem::last_write_time 的重大更改

c++ - 链接不同C++标准编译的库有没有隐患?

c++ - iOS设备执行并发任务时如何设置合适的线程数?

c++ - 如何将 atof 的结果输出为 1.0 而不是 1

c++ - 在类中调用自由 float 函数

C++ std::variant 与 std::any

c++ - 递归编译结构的大小减去填充

c++ - 推导出具有默认模板参数的模板函数指针的模板参数

c++ - 运算符重载使用operator +作为类模板

c++ - 当你通过引用返回对象时,你什么时候需要担心对象会被销毁?