如何遍历 C++ 中的对象列表? [英] How to iterate through a list of objects in C++?
本文介绍了如何遍历 C++ 中的对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 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.
我一直在尝试这个,其中 data
是一个 std::list
和 Student
一个类.
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;
}
并收到以下错误:
error: base operand of ‘->’ has non-pointer type ‘Student’
推荐答案
离你很近了.
std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
std::cout << it->name;
}
请注意,您可以在 for
循环中定义 it
:
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;
}
如果您使用的是 C++11,那么您可以使用基于范围的 for
循环:
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;
}
这里 auto
自动推导出正确的类型.你可以写 Student const&我
代替.
Here auto
automatically deduces the correct type. You could have written Student const& i
instead.
这篇关于如何遍历 C++ 中的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文