I'm very new to C++ and struggling to figure out how I should iterate through a list of objects and access there members.
I've been trying this where data
is the 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’
-> 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'
Since C++ 11, you could do the following:
for(const auto& student : data)
{
std::cout << student.name << std::endl;
}
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;
}
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
Source: Stackoverflow.com