2

std::accumulateは、3 つまたは 4 つの引数を取ることができるはずです。前者の場合は、コンテナに数値を追加したい場合です。後者の場合は、最初に関数を適用してから追加する場合です。私は、ランダムな double のベクトルを生成し、それらに対して何らかの処理を行うコードを作成しましstd::transformstd::accumulate。 - の引数バージョンstd::accumulate

ステップ 3 以外はすべて機能します。http://www.cplusplus.com/reference/numeric/accumulate/にあるサンプル コードを見ると、これが機能しない理由はわかりませんが、コンパイル時に「Too many arguments error」が発生します(XCodeを使用しています。何らかの理由で行番号がわかりませんが、2番目の使用法に絞り込みました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;
}
4

1 に答える 1

8

そのstd::accumulateオーバーロードの 4 番目の引数は、二項演算子である必要があります。現在、単項を使用しています。

std::accumulateコンテナ内の連続する要素間で二項演算を実行するため、二項演算子が必要です。4 番目の引数は、デフォルトの二項演算である加算を置き換えます。単項演算を適用してから加算を実行するわけではありません。要素を二乗してから追加したい場合は、次のようなものが必要になります

double addSquare(double a, double b)
{
  return a + b*b;
}

それで

double x = std::accumulate(original.begin(), original.end(), 0.0, addSquare);
于 2013-01-20T22:39:06.553 に答える