将两个矢量相加

Adding two vectors together

本文关键字:两个      更新时间:2023-10-16

所以我在构建代码时遇到了这个问题。这是的问题

这项工作是基于运算符重载的,您需要构建一个字符串计算器,计算器可以为字符串变量执行加减函数(只有
字符和字符串的空格)。

我遇到的问题是,当我试图将我创建的两个向量相加时。例如,向量A=<1,2,3>和向量B=<1,2>。我希望A+B等于<2,4,3>。但当我这样做的时候,我得到的输出是2。这是我的密码。

#include<iostream>
#include<string>
#include<vector>
using namespace std;
string a;
string b;
int k, j, ab, x;
vector <int> scab;
int main() {
cout << "Input A: ";
getline(cin, a);
cout << "Input B: ";
getline(cin, b);
    vector<int> sca;
    vector<int> scb;
    // For A
    for (int i = 0; i < a.size(); i++) {
        sca.push_back(static_cast <int> (a[i]));
    }
    cout << "Input A: ";
    for (int j = 0; j < sca.size(); ++j)
    {
        cout << sca[j] << "t";
    }
    cout << endl;
    cout << endl;
    // For B
    for (int p = 0; p < b.size(); p++) {
        scb.push_back(static_cast <int> (b[p]));
    }
    cout << "Input B: ";
    for (int j = 0; j < scb.size(); ++j)
    {
        cout << scb[j] << "t";
    }
    scab.push_back(sca[j] + scb[j]);
    cout << endl;
    cout << endl;
cout << "A+B: " << scab[j] << "t";
    system("pause");

}

提前感谢。

尝试使用标准库中的更多内容以使其更容易:

auto size = std::max(sca.size(), scb.size());
sca.resize(size);
scb.resize(size);
auto scab = std::vector<int>(size);
std::transform(sca.begin(), sca.end(), scb.begin(), scab.begin(), std::plus<int>());

从代码中可以看出,矢量包含表示数字的字符。此外,您还应该考虑可能发生的溢出。

这里有一个演示程序,展示了如何为这样的向量重载这样的运算符cna。

#include <iostream>
#include <algorithm>
#include <vector>
std::vector<int> operator +( const std::vector<int> &a, const std::vector<int> &b )
{
    auto less = []( const std::vector<int> &a, const std::vector<int> &b )
    {
        return a.size() < b.size();
    };
    std::vector<int> c( std::min( a, b, less ) );
    c.resize( std::max( a.size(), b.size() ), '0' );
    int overflow = 0;
    auto plus = [&overflow]( int x, int y )
    {
        int sum = x - '0' + y - '0' + overflow;
        overflow = sum / 10;
        return sum % 10 + '0';
    };
    std::transform( c.begin(), c.end(), std::max( a, b, less ).begin(), c.begin(), plus );
    if ( overflow ) c.push_back( overflow + '0' );
    return c;
}    
int main()
{
    std::vector<int> a( { '1', '2', '3' } );
    std::vector<int> b( { '1', '9' } );
    for ( int x : a ) std::cout << static_cast<char>( x ) << ' ';
    std::cout << std::endl;
    std::cout << "+" << std::endl;
    for ( int x : b ) std::cout << static_cast<char>( x ) << ' ';
    std::cout << std::endl;
    std::cout << "=" << std::endl;
    std::vector<int> c;
    c = a + b;
    for ( int x : c ) std::cout << static_cast<char>( x ) << ' ';
    std::cout << std::endl;
}

程序输出为

1 2 3 
+
1 9 
=
2 1 4 

如果矢量包含整数值而不是字符,则代码会更简单。

或者向量可以声明为具有类型std::vector<char>