I have two vectors myVect
, myTransf
. I am trying to make the transfer money from one account to another account, I tried two loops where the money will be transferred as soon as the account number match, I am trying so but I think because the iterators are no supposed to change the container the values so they can't change the values. How can I modify the vector values?
#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;
}
Aucun commentaire:
Enregistrer un commentaire