将两个向量相加 [英] Adding two vectors together

查看:119
本文介绍了将两个向量相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have this problem I ran into when building a code. This the question

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

This work is based on operator overloading, you need to build a string calculator, the calculator can do add and minus functions for string variables (there will be only
characters and space for the string).

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

The problem I ran into is when I try to add the two vectors I created together. For example, Vector A= <1,2,3> and Vector B= <1,2>. I want A+B to equal <2,4,3>. But when I do that I get an output of 2. Here is my code.

#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");

}

先谢谢你.

推荐答案

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

Try to use more from the standard library to make it easier:

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>());

这篇关于将两个向量相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆