简体   繁体   English

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

[英]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.

相关问题 “for_each_n”不是 C++17 中“std”的成员 - 'for_each_n' is not a member of 'std' in C++17 有什么方法可以结合 std::istream_iterator 和 std::for_each_n() 吗? - Any way to combine std::istream_iterator and std::for_each_n()? 为什么endl(std :: cout)会编译 - Why does endl(std::cout) compile 为什么std :: swap不能与std :: bitset一起使用 <n> 内容? - Why std::swap does not work with std::bitset<n> content? 为什么 std::set <array<int,n> &gt; 工作但不是 std::unordered_set <array<int,n> &gt;? </array<int,n></array<int,n> - Why does std::set<array<int,N>> work but not std::unordered_set<array<int,N>>? 为什么std :: less <Eigen::VectorXd> 无法编译? - Why does std::less<Eigen::VectorXd> fail to compile? 为什么这个简单的程序使用std :: rotate不能编译? - Why does this simple program using std::rotate not compile? 为什么在三元运算符中使用std :: ostream不能编译? - Why does std::ostream not compile when used in ternary operator? 为什么std::visit in a unsatisfied concept会导致gcc编译错误 - Why does std::visit in an unsatisfied concept cause a compile error in gcc 为什么boost :: asio :: io_service不能用std :: bind编译? - Why does boost::asio::io_service not compile with std::bind?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM