Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a list of objects in C++?

I'm very new to C++ and struggling to figure out how I should iterate through a list of objects and access their members.

I've been trying this where data is a std::list and Student a class.

std::list<Student>::iterator<Student> it; for (it = data.begin(); it != data.end(); ++it) {     std::cout<<(*it)->name; } 

and getting the following error:

error: base operand of ‘->’ has non-pointer type ‘Student’ 
like image 304
Gottfried Avatar asked Mar 08 '14 12:03

Gottfried


People also ask

What is the best way to iterate a list?

The best way to iterate the list in terms of performance would be to use iterators ( your second approach using foreach ).


2 Answers

You're close.

std::list<Student>::iterator it; for (it = data.begin(); it != data.end(); ++it){     std::cout << it->name; } 

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){     std::cout << it->name; } 

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {     std::cout << i.name; } 

Here auto automatically deduces the correct type. You could have written Student const& i instead.

like image 119
Simple Avatar answered Sep 25 '22 16:09

Simple


Since C++ 11, you could do the following:

for(const auto& student : data) {   std::cout << student.name << std::endl; } 
like image 45
jhill515 Avatar answered Sep 25 '22 16:09

jhill515