如何在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 there members.
我一直在尝试这个其中'data'是列表,'student'是一个类。
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;
}
并收到以下错误
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;
}
请注意,你可以定义它
里面的
循环:
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;
}
这里自动
自动推断出正确的类型。你可以写学生const&我
而不是。
Here auto
automatically deduces the correct type. You could have written Student const& i
instead.
这篇关于如何在c ++中迭代对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文