使用count_if()查找vector中相同字符串时Lambda捕获错误如何解决
错误原因
该报错的核心原因是lambda表达式内部使用了外部作用域定义的str变量,但没有在lambda的捕获列表中声明对该变量的捕获,C++标准不允许lambda隐式使用未捕获的外部变量。
variable 'str' cannot be implicitly captured in a lambda with no capture-default specified
修复方法
仅需要在lambda的捕获列表中声明需要捕获str即可,当前场景你只需要读取str的值,按值捕获就可以满足需求,把lambda的开头[]修改为[str]即可。
修复后的完整代码如下:
#include <vector> #include <string> #include <algorithm> #include <iostream> int main() { std::vector<std::string> hello{"Mon","Tue", "Wes", "perfect","Sun"}; for (unsigned int i = 0; i < hello.size(); i++) { int n=0; std::string str=hello[i]; // 在捕获列表中添加str完成捕获 n=std::count_if(hello.begin(),hello.end(),[str](const std::string& s){return s==str;}); std::cout << str << " 出现次数: " << n << std::endl; } return 0; }
可选优化点
- 如果想减少拷贝开销,也可以按const引用捕获
str,写法为[&str],当前场景下str的生命周期完全覆盖count_if的执行周期,不会出现悬垂引用问题,执行效率更高。 - lambda的入参改为
const std::string& s可以避免遍历过程中对每个字符串做不必要的拷贝,进一步提升执行效率。
内容的提问来源于stack exchange,提问作者Steven
相关产品推荐
相关产品推荐

