【问题标题】:Iterating over two vectors and changing the values迭代两个向量并改变值
【发布时间】:2020-08-08 14:58:52
【问题描述】:

我有两个向量 myVectmyTransf。我正在尝试将资金从一个帐户转移到另一个帐户。我尝试了两个循环,一旦帐号匹配,钱就会被转移。我正在尝试,但我无法更改容器值。如何修改向量值?

#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&amp;
  • 你没有在代码中使用迭代器。

标签: c++ visual-studio c++11 vector c++14


【解决方案1】:

如果你想修改一个范围,你需要像这样引用每个元素:

for (auto &y : vect)
   // changing y modifies vect

改变它和它works

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2013-10-23
    • 2010-11-17
    • 1970-01-01
    • 2021-12-20
    • 2013-04-20
    • 1970-01-01
    相关资源
    最近更新 更多