首页 > 解决方案 > C ++尝试使用max和accumulate函数

问题描述

我是 C++ 新手,这是我尝试编写的第一个程序。在下面的代码中,我想模拟期权的价格并计算其价值。我收到累积函数的错误。

我已经尝试过std::maxstd::accumulate但它们效果不佳。

#include <iostream>
#include <algorithm>
#include <cmath>
#include<random>
#include<numeric>
#include<vector>
using namespace std;

double mc(int S, int K, float r, float vol, int T, int sim, int N){
mt19937 rng;
normal_distribution<>ND(0,1);
ND(rng);
std::vector<double> s(sim);
double dt = T/N;
for(int i =0;i<sim;i++)
{
    std::vector<double> p(N);
    p[0]=S;
    for(int k = 0;k<N;k++)
    {
        double phi = ND(rng);
        p[i+1] = p[i]*(1+r*dt+vol*phi*sqrt(dt));

    }
    s[i] = max(p[N-1]-K,0);

}
        float payoff = (accumulate(s)/sim)*exp(-r*T);
        return payoff;
}

int main(){
    cout << mc(100,100,0.05,0.2,1,100,100) << endl;
    return 0;
}

错误:

> test1.cpp:26:21: error: no matching function for call to 'accumulate'
>     float payoff = (accumulate(s)/sim)*exp(-r*T);
>                     ^~~~~~~~~~ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/numeric:158:1:
> note: candidate function template not viable: requires 3 arguments,
> but 1 was provided accumulate(_InputIterator __first, _InputIterator
> __last, _Tp __init) ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/numeric:168:1:
> note: candidate function template not viable: requires 4 arguments,
> but 1 was provided accumulate(_InputIterator __first, _InputIterator
> __last, _Tp __init, _BinaryOperation __binary_op) ^ 2 errors generated.

编辑:固定最大功能。它使用 0.0 而不是 0

标签: c++compiler-errorsmaxaccumulate

解决方案


阅读 C++ 标准库文档std::accumulate将解决您的问题。但是由于您是该语言的新手,而且 STL 对于初学者来说有点难以解读,这里是阅读文档的方法。

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

std::accumulate是一个泛型函数,所以它是在泛型类型上模板化的,T. 在你的情况下,T = double. 它需要两个输入迭代器,firstandlast和一个初始值init,类型为T = double。所以,下面是一个关于如何积累std::vector<double>.

std::vector<double> v = { 1., 2., 3. };
double result = std::accumulate(v.begin(), v.end(), 0.);

注意vector::beginvector::end迭代器分别返回到容器的开头和结尾。

将您的调用替换为accumulate使用迭代器并提供初始值。


推荐阅读