C++代码报错error C2064:表达式未计算为接受1个参数的函数求排查
解决C++ error C2064: term does not evaluate to a function taking 1 arguments错误
问题分析
你的代码触发C2064错误有两个核心问题:
lambda不符合
std::for_each的回调要求std::for_each要求第三个参数是能接收单个参数的可调用对象,这个参数对应遍历过程中当前迭代器指向的元素。但你定义的lambda没有声明任何参数,编译器无法将for_each传递的元素匹配到这个lambda,直接触发错误。捕获的迭代器无法实现遍历
即便忽略参数问题,你捕获的it是初始的crbegin()迭代器,在lambda内部不会随着for_each的遍历自动移动,最终只会重复输出容器的第一个反向元素,达不到遍历所有元素的目的。
修正方案
推荐使用第一种简洁且符合for_each设计意图的写法:
#include <iterator> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { vector<int> ivec{ 1,1,2,3,5,8,13,21,34,55,89 }; vector<int>::const_reverse_iterator it = ivec.crbegin(), rend = ivec.crend(); // 接收for_each传入的当前元素,直接输出 for_each(it, rend, [](int val){cout << val << " "; }); cout << endl; return 0; }
如果一定要通过迭代器实现(不推荐,违背for_each的设计逻辑),可以通过捕获迭代器的引用并标记lambda为mutable来实现:
#include <iterator> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { vector<int> ivec{ 1,1,2,3,5,8,13,21,34,55,89 }; vector<int>::const_reverse_iterator it = ivec.crbegin(), rend = ivec.crend(); // 捕获it的引用,输出后手动自增迭代器 for_each(it, rend, [&it]() mutable {cout << *it << " "; ++it; }); cout << endl; return 0; }
内容的提问来源于stack exchange,提问作者gaofeng
相关产品推荐
相关产品推荐

