【发布时间】:2020-08-08 14:58:52
【问题描述】:
我有两个向量 myVect 和 myTransf。我正在尝试将资金从一个帐户转移到另一个帐户。我尝试了两个循环,一旦帐号匹配,钱就会被转移。我正在尝试,但我无法更改容器值。如何修改向量值?
#include <iostream>
#include<vector>
using namespace std;
struct account_info{
int acc;
int bal;
};
struct transfer {
int from;
int to;
int amt;
};
using myVect = vector<account_info>;
using myTransf = vector<transfer>;
int main()
{
myVect vect;
vect.push_back({ 1,20 }); // Account 1 has 20 dollar
vect.push_back({ 3,40 }); // Account 2 has 40 dollar
vect.push_back({ 5,60 }); // Account 3 has 60 dollar
for (auto x : vect)
{
cout << x.acc << " " << x.bal << endl;
}
cout << "Values will change now \n";
myTransf trans;
trans.push_back({ 1, 3, 1 }); // from account 1 to account 3 transfer 1 dollar
trans.push_back({ 3, 5, 1 }); // from account 3 to account 5 transfer 1 dollar
// I was looking for an optimized code this is the best O(MxN) I could come up with now the problem is I can't able to make modifications inside the "vect"
for (auto x : trans)
{
bool eq1 = false;
bool eq2 = false;
for (auto y : vect)
{
// If account match then withdraw the money from the "from" account
if (x.from == y.acc)
{
y.bal -= x.amt; // Values are not changing as these are the operators
eq1 = true;
}
// If account match then deposit the money to the "to" account
else if (x.to == y.acc)
{
y.bal += x.amt; // Values are not changing as these are the operators
eq2 = true;
}
if (eq1 && eq2)
{
break;
}
}
}
for (auto x : vect)
{
cout << x.acc << " " << x.bal << endl;
}
return 0;
}
【问题讨论】:
-
你需要在 range-for 循环中使用
auto&。 -
你没有在代码中使用迭代器。
标签: c++ visual-studio c++11 vector c++14