【发布时间】:2014-12-23 13:09:19
【问题描述】:
我是编程新手,我正在尝试查看这本 C++ Premier Plus 书籍,但是在检查 LAMBDA 部分时,我在 VBS 2013 上遇到了编译错误
// use captured variables
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>
const long Size = 390000L;
int main()
{
using std::cout;
std::vector<int> numbers(Size);
std::srand(std::time(0));
std::generate(numbers.begin(), numbers.end(), std::rand);
cout << "Sample size = " << Size << '\n';
// using lambdas
/*int count3 = std::count_if(numbers.begin(), numbers.end(),
[](int x){return x % 3 == 0; });
cout << "Count of number divisible by 3: " << count3 << '\n';*/
int count13 = 0;
std::count_if(numbers.begin(), numbers.end(),
[&count13](int x){count13 += x % 13 == 0; });
cout << "count of number divisible by 13: " << count13 << '\n';
// using a single lambda
/*int count3 = 0;
int count13 = 0;
std::for_each(numbers.begin(), numbers.end(),
[&](int x){count3 += x % 3 == 0; count13 += x % 13 == 0; });
cout << "Count of number divisible by 3: " << count3 << '\n';
cout << "Count of number divisible by 13: " << count13 << '\n';
*/
return 0;
}
未注释的部分是我得到的:“void”类型的条件表达式是非法的。我认为编译器正在尝试将 lambda 表达式closurert{body} 作为条件运算符 Exp1 读取? Exp2 : Exp3;.
这个练习的想法是,当使用 2+ lambda 或 1 个联合 lambda 时,它应该返回相同的值输出,而在我的情况下它不会。
感谢您的启迪......
【问题讨论】:
-
您忘记了 lambda 中的 return 语句。为了清楚起见,您可能需要包含一些括号。
-
如果你使用
count_if,你应该输入计数元素的条件作为第三个参数,如果你想在捕获的变量中计算它们,也许你需要for_each。 -
感谢 Borgleader,只是没注意到...