【问题标题】:2D vector ignores assigned values?二维向量忽略分配的值?
【发布时间】:2015-11-07 13:16:17
【问题描述】:

我正在研究一个表示多项式的简单类。我将 x 的系数和等效幂存储在 2D 向量中。分配某些术语的方式必须如测试文件中所示。它需要我提供的一些运算符重载。问题是除了最后一个之外,它还分配了适当的系数,另外每个项都具有第一个分配值的 x 次幂。

期望的输出:

多项式 p1:2x^3 + 3.6x + 7x^0

多项式 p2:3x^1 + 6x^2 + 1x^4

实际输出:

多项式 p1:5x^3 + 2x^3 + 3.6x^3

多项式 p2:5x^1 + 3x^1 + 6x^1

你知道这是怎么回事吗?我

多项式.cpp

double & Polynomials::operator[]( int power_of_x ){


    this->coeff_and_power.push_back(5.0);  // dummy variable 5.0 just to alloc 'cell' for coefficient

    this->coeff_and_power.push_back( (double) power_of_x ); //assigning power of x

    this->polynomial_terms.push_back( coeff_and_power );    // polynomial_terms vector contains collection of 2 elements vectors( coefficient and power ) indicating certain term of a function


    return (coeff_and_power[0]);  //coefficient to be assigned in main(returning by reference) function
}



std::ostream& operator<<(std::ostream& out, const Polynomials & toWrite){


    for(unsigned int i = 0; i < toWrite.polynomial_terms.size(); i++){

            if(i){
                out<<" + ";
            }

            out<<toWrite.polynomial_terms[i][0]<<"x^"<<toWrite.polynomial_terms[i][1];          
    }

    return out;
}

test.cpp

#include <iostream>
#include "Polynomials.h"

using namespace std;

int main(void) {

Polynomials p1;                             
p1[3] = 2; p1[1] = 3.6; p1[0] = 7;                

Polynomials p2;                            
p2[1] = 3; p2[2] = 6; p2[4] = 1;                 

cout << "Polynomial p1: " << p1 << endl;              
cout << "Polynomial p2: " << p2 << endl;

}

【问题讨论】:

  • 使用调试器并逐行执行。
  • 为什么我会得到负利率?解决方案是如此明显还是什么?
  • 欢迎来到 SO!由于您没有给我们重现错误的机会,因此可能会累积反对票;例如在我的答案中,我必须做一些猜测工作,并冒着因为我猜错而导致对该答案投反对票的风险。

标签: c++ vector operator-overloading


【解决方案1】:

在您的operator[] 中超载您push_back(),但无条件。

return coeff_and_power[0];

返回front 进行分配

顺便说一句

this->polynomial_terms.push_back( coeff_and_power )

推送一个副本,而不是一个引用,因为 polynomial_terms 具有类似的行为,例如标准:向量。

【讨论】:

    猜你喜欢
    • 2016-03-28
    • 2023-03-10
    • 2016-08-11
    • 2017-12-26
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多