使用 std::累积,得到一个"too many arguments"错误
using std::accumulate, getting a "too many arguments" error
std::accumulate
应该能够接受三个或四个参数。在前一种情况下,它只是当你想在容器中添加数字时;在后一种情况下,它是当你想先应用一个函数,然后添加它们。我已经编写了代码,生成一个随机双精度向量,然后对它们做一些事情:首先它使用std::transform
执行x->x^2转换,然后将它们与std::accumulate
相加,最后使用std::accumulate
的四参数版本将两个动作组合为一个。
除了步骤3,其他都可以。看看在http://www.cplusplus.com/reference/numeric/accumulate/上找到的示例代码,我看不出这不应该工作的任何理由,但我在编译时得到"太多参数错误"(我使用XCode)。由于某些原因,它没有告诉我行号,但我已经将其缩小到std::accumulate
的第二次使用。见解吗?
#include <numeric>
#include <time.h>
#include <math.h>
using std::vector;
using std::cout;
using std::endl;
double square(double a) {
return a*a;
}
void problem_2_1() {
vector<double> original;
//GENERATE RANDOM VALUES
srand((int)time(NULL));//seed the rand function to time
for (int i=0; i<10; ++i) {
double rand_val = (rand() % 100)/10.0;
original.push_back(rand_val);
cout << rand_val << endl;
}
//USING TRANSFORM
vector<double> squared;
squared.resize(original.size());
std::transform(original.begin(), original.end(), squared.begin(), square);
for (int i=0; i<original.size(); ++i) {
std::cout << original[i] << 't' << squared[i] << std::endl;
}
//USING ACCUMULATE
double squaredLength = std::accumulate(squared.begin(), squared.end(), 0.0);
double length = sqrt(squaredLength);
cout << "Magnitude of the vector is: " << length << endl;
//USING 4-VARIABLE ACCUMULATE
double alt_squaredLength = std::accumulate(original.begin(), original.end(), 0.0, square);
double alt_length = sqrt(alt_squaredLength);
cout << "Magnitude of the vector is: " << alt_length << endl;
}
std::accumulate重载的第四个实参必须是二进制操作符。当前您使用的是一元。
std::accumulate
在容器中的连续元素之间执行二进制操作,因此需要使用二进制操作符。第四个参数取代默认的二进制操作,加法。它不会先应用一元运算,然后再执行加法。如果你想把元素平方然后相加,你需要像
double addSquare(double a, double b)
{
return a + b*b;
}
然后double x = std::accumulate(original.begin(), original.end(), 0.0, addSquare);
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '