添加两个多项式并正确显示结果

Adding two polynomials and displaying the result properly

我的代码相当简单:

    #include <cstdlib>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <numeric>
    #include <cmath>

using namespace std;

int main() {

    int sizeOfPoly1;
    cout<<"Size of first polynomial: ";
    cin>>sizeOfPoly1;
    vector<int> poly1(sizeOfPoly1);
    cout<<"constant =";
    cin>>poly1[0];
    for (int i = 1; i <= (sizeOfPoly1-1); ++i)
    {
        cout<<"Insert x^"<<i<<": ";
        cin>>poly1[i];
    }

    int sizeOfPoly2;
    cout<<"Size of second polynomial: ";
    cin>>sizeOfPoly2;
    vector<int> poly2(sizeOfPoly2);
    cout<<"constant =";
    cin>>poly2[0];
    for (int i = 1; i <= (sizeOfPoly2-1); ++i)
    {
        cout<<"Insert x^"<<i<<": ";
        cin>>poly2[i];
    }


    int sizeOfResult;

    //verifies which polynomial has more elements and makes the result the size of the biggest one
    if (poly1.size() >= poly2.size())  sizeOfResult = poly1.size();
    else sizeOfResult = poly2.size();
    vector<int> result(sizeOfResult);


    for(int i = 0; i<sizeOfResult; ++i) { result[i] = poly1[i] + poly2[i]; }
    cout<<"Sum of the two polynomials: ";

    for(int i = 0; i<sizeOfResult; ++i)
    {
        switch(i){
            case 0:  cout<<result[i]<<" "; break;
            case 1:  cout<<result[i]<<"x"<<" "; break;
            default: cout<<result[i]<<"x^"<<i<<" "; break;
        }

    }


    return 0;
}

我想要做的是让用户输入他们的多项式大小,然后输入常数,x^1,x^2 等等,然后 return 两者的总和多项式。此代码当前生成一些奇怪的东西,例如: Sum of the two polynomials: 2 4x 6x^2 8x^3 1772060652x^4 当一个多项式向量的元素多于另一个时,如何防止发生此输出错误?

只需将它们设为相同大小并使用 std::transform:

const auto sizeOfResult = std::max( poly1.size(), poly2.size() );
poly1.resize( sizeOfResult );
poly2.resize( sizeOfResult );

vector<int> result(sizeOfResult);
std::transform( poly1.begin(), poly1.end(), poly2.begin(), result.begin(),
                []( int a, int b ) { return a+b; } );

这是一个简单的解决方案,但开销很小。更有效的解决方案:

auto p = poly1.size() < poly2.size() ? std::tie( poly1, poly2 ) : std::tie( poly2, poly1 );
std::vector<int> result( std::get<1>( p ) );
for( size_t i = 0; i != std::get<0>( p ).size(); ++i )
    result[i] += std::get<0>( p )[i];

live example