所以我在构建代码时遇到了这个问题.这个问题
这项工作是基于运算符重载,你需要建立一个字符串计算器,计算器可以为字符串变量做加减函数(字符串只有
字符和空格).
我遇到的问题是当我尝试添加我一起创建的两个向量时.例如,矢量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");
Run Code Online (Sandbox Code Playgroud)
}
先谢谢你.
尝试使用标准库中的更多内容来简化:
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>());
Run Code Online (Sandbox Code Playgroud)