+ 2

Object Iteration?

Is there a way to iterate through objects in C++? Like, say I want to print the name of each person object in the person class. like loop through and do something like Person.printName(); for each object?

8th Mar 2019, 12:13 AM
Daniel Cooper
Daniel Cooper - avatar
3 Answers
+ 10
Daniel Cooper Try to use vector of Person in main procedure, as follows: vector<Person> vp {{"Daniel"}, {"James"}, {"Lily"}, {"Breanna"}}; for(Person& p : vp) p.printName(); P.S. Don't forget to include <string> and <vector> : )
8th Mar 2019, 3:31 AM
Ipang
+ 2
https://code.sololearn.com/cGbvbk6urY2U/?ref=app Here's an example of my question. I created a person class with about 4 people. Is it possible to use a loop to print the name of each person? If so, how?
8th Mar 2019, 2:49 AM
Daniel Cooper
Daniel Cooper - avatar
+ 2
I'm seeing attempts online to use a vector or a list of class objects, but I can't figure out how I'd put an object into a vector after it's created.
8th Mar 2019, 3:19 AM
Daniel Cooper
Daniel Cooper - avatar