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’
The best way to iterate the list in terms of performance would be to use iterators ( your second approach using foreach ).
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.
Since C++ 11, you could do the following:
for(const auto& student : data) { std::cout << student.name << std::endl; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With