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

C++For LoopC++11StlIterator

C++ Problem Overview


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’

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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

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

Solution 3 - C++

-> it works like pointer u don't have to use *

for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'

Solution 4 - C++

It is also worth to mention, that if you DO NOT intent to modify the values of the list, it is possible (and better) to use the const_iterator, as follows:

for (std::list<Student>::const_iterator it = data.begin(); it != data.end(); ++it){
    // do whatever you wish but don't modify the list elements
    std::cout << it->name;
}

Solution 5 - C++

if you add an #include <algorithm> then you can use the for_each function and a lambda function like so:

for_each(data.begin(), data.end(), [](Student *it) 
{
    std::cout<<it->name;
});

you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm

and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGottfriedView Question on Stackoverflow
Solution 1 - C++SimpleView Answer on Stackoverflow
Solution 2 - C++jhill515View Answer on Stackoverflow
Solution 3 - C++RadekView Answer on Stackoverflow
Solution 4 - C++Guy AvrahamView Answer on Stackoverflow
Solution 5 - C++yoni framView Answer on Stackoverflow