c++ - while()中调用了lambda表达式,为什么要在lambda表达式后面加()
问题描述
while ([&s]()->bool {
cout << "Please Input you word<input \"q \" to exit>:";
return (cin >> s) && (s != "[enter image description here][1]q");
}())
解决方案
Lambda 表达式是函数定义。当你调用一个函数时,你必须使用括号,但是当你将函数作为参数传递时,你只使用名字。如果我们将 lambda 函数存储在一个名为“条件”的变量中,您可能会更好地看到这一点:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s{};
auto condition = [&s]() -> bool {
cout << "Please Input you word:";
return ((cin >> s) && (s != "enter image description here"));
};
while (condition()) {
}
return (0);
}
参考:http ://en.cppreference.com/w/cpp/language/lambda
这也可以写成:
#include <iostream>
#include <string>
int main() {
std::string s{};
while ([&s] {
std::cout << "Please Input you word:";
return ((std::cin >> s) && (s != "enter image description here"));
}()) {
}
return (0);
}
推荐阅读
- python - 具有指数衰减的正弦函数的非线性最小二乘拟合误差
- c++ - 如何使用 rwcstring 替换所有出现的“\\”
- refactoring - 这是什么语言?(写于 1985 年)
- xml - 如何向 wsdl 文件/soap api 添加基本身份验证?
- keycloak - Keycloak 通过分片创建领域
- haskell - foldl/foldr 不会命中 stackoverflow
- caching - TYPO3 缓存预热与爬虫不工作
- google-sheets - 如何从任何块 html 元素导入谷歌表格?
- c# - 在 openTK 中旋转图像
- python - 使用 beautifulsoup 提取网页中所有 url 中的公司名称和其他信息