【发布时间】:2019-08-27 02:46:57
【问题描述】:
我有一个整数153,我需要判断他是否等于pow之和(digit,digits)。所以153 = 1^3 + 5^3 + 3^3 = 153 返回true。
我选择使用基本循环查找位数,然后将所有整数推入一个向量中,这样我就可以使用 std::for_each 函数迭代并在每个元素上使用 pow()。
我面临的问题是每个元素的变化。我还不想诉诸for-loop,但我似乎无法通过for_each 弄清楚如何做到这一点。
错误在代码中注释。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <numeric>
bool narcissistic(int value)
{
int k{};
std::vector <int> sum{};
while (value > 0) {
k++;
sum.push_back(value % 10);
value /= 10;
}
std::for_each(sum.begin(), sum.end(), [](int& n) {pow(n, k); }); // error: 'k' is not captured
// (warning) note: the lambd has no capture-default
if (std::accumulate(sum.begin(), sum.end(), 0) == value) return true;
return false;
}
int main()
{
std::cout << narcissistic(153) << std::endl;
return 0;
}
【问题讨论】:
-
What is a lambda expression in C++11? 的可能重复错误消息为您提供了关键字“捕获”——在答案中查找该词。
标签: c++ algorithm lambda c++14 stdvector