Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading