gpt4 book ai didi

c++ - Vector is not incrementable 错误

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:59 25 4
gpt4 key购买 nike

我正在用 C++ 编写一个程序来实现 Newton-Raphson 方法等,并且我已经定义了一个多项式类:

#include <iostream>
#include <algorithm>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <set>

using namespace std;

class polynomial{

using pair_dd = pair<double, double>;

public:
polynomial(const vector<pair_dd>& v) : m_coeff(simplify(v)) {} // constructor
polynomial(const polynomial& p) : m_coeff(p.m_coeff){} // copy constructor
polynomial derivative() const{ // computes derivative
vector<pair_dd> dcoeff;
for_each(begin(m_coeff), end(m_coeff), [&](pair_dd p){
dcoeff.emplace_back(pair_dd(p.first*p.second, p.second - 1));
});
return polynomial(dcoeff);
}
double apply(double x) const{ // applies poly to argument
auto sum(0.0);
for_each(begin(m_coeff), end(m_coeff), [&](pair_dd p){
sum += p.first*pow(x, p.second);
});
return sum;
}
void write() const{ // prints polynomial
// function just for testing
for (const auto& term : m_coeff)
cout << term.first << "x^" << term.second << " +";
cout << endl;
}

private:
polynomial(); //forbid empty constructor
vector<pair_dd> m_coeff;
vector<pair_dd> simplify(const vector<pair_dd>& v) const{

set<double> exp; // set of exponents
for (const auto& term : v)
exp.insert(term.second);

vector<pair_dd> ret; // final simplified vector
vector<pair_dd> temp; // temporary object

for (const auto& power : exp){
copy_if(begin(v), end(v), begin(temp), [&](const pair_dd p){
return (p.second == power);
});
// combine terms
auto sum(0.0);
for (auto& p : temp)
sum += p.first;
ret.push_back(pair_dd(sum, power));
temp.clear();
}
return ret;
}
};


int main(){

vector<pair<double, double>> vec;
vec.push_back(pair<double, double>(5,1)); // 5x
vec.push_back(pair<double, double>(10, 1)); // 10x
vec.push_back(pair<double, double>(3, 2)); // 3x^2

polynomial poly(vec);

// should write 15x + 3x^2

poly.write();
return 0;
}

我遇到的问题是 simplify 函数,它会在运行时在 copy_if 位置产生错误。据说,

vector temp is not incrementable

在 Visual Studio 中。我的算法的工作方式是将所有具有相同 x 次方的项收集在一个集合中(因为我们只需要唯一元素)。随后,我遍历指数集,使用成对 vector 上的 copy_if 将具有相同指数的所有项组合在一起,然后将它们组合并放入最终 vector 中。

我已尝试保留和调整临时 vector 的大小。

最佳答案

copy_if不会分配内存,它假定 temp已经调整大小,但事实并非如此。您可以使用 std::back_inserter 来自 <iterator> .

copy_if(begin(v), end(v), back_inserter(temp), [&](const pair_dd p){
return (p.second == power);
});

关于c++ - Vector is not incrementable 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com