Search code examples
c++stdvector

Edit Object in Vector and return Vector


I am new to programming. I am trying to make a Banking application, where a User enters their name and gets a Username set. I am messing around with Classes for the first time.

  1. I am trying to pass a std::vector to a function to add Data into it. Do I have to return the values that I want to set into the Vector? Or can I just edit the Vector in the subfunction, since a Vector is stored on the Heap?

  2. How can I modify the Attributes of an Object in a Vector?

class Account {int something{}; };
Account Frank;
Frank.something =....

How can I do that in Vectors?


Solution

  • You can pass a non-const reference of your vector to your function, e.g.

    void add_value(std::vector<int>& values, int value) {
        values.push_back(value);
    }
    
    // later
    std::vector<int> values;
    add_value(values, 5);
    // values now contains {5}
    

    If you have a vector of objects you can first index one of them, then call a method or attribute

    std::vector<Account> accounts;
    // ... gets filled ...
    accounts[i].do_something();  // call method
    accounts[i].name;  // access public member