如何遍历 C++ 中的对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22269435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate through a list of objects in C++
提问by Gottfried
I'm very new to C++ and struggling to figure out how I should iterate through a list of objects and access there members.
我对 C++ 很陌生,正在努力弄清楚我应该如何遍历对象列表并访问那里的成员。
I've been trying this where data
is the list and student
a class.
我一直在尝试这个data
列表和student
课程在哪里。
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'
回答by Simple
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:
请注意,您可以it
在for
循环内定义:
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:
如果您使用的是 C++11,那么您可以使用基于范围的for
循环:
for (auto const& i : data) {
std::cout << i.name;
}
Here auto
automatically deduces the correct type. You could have written Student const& i
instead.
这里auto
自动推导出正确的类型。你本来可以写的Student const& i
。
回答by jhill515
Since C++ 11, you could do the following:
从 C++ 11 开始,您可以执行以下操作:
for(const auto& student : data)
{
std::cout << student.name << std::endl;
}
回答by Guy Avraham
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:
还值得一提的是,如果您不打算修改列表的值,则可以(并且更好)使用const_iterator
,如下所示:
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;
}
回答by Radek
-> 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'
回答by yoni fram
if you add an #include <algorithm>
then you can use the for_each
function and a lambda function like so:
如果添加一个,#include <algorithm>
则可以使用该for_each
函数和一个 lambda 函数,如下所示:
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
您可以在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
以及关于 cpp 中的 lambda 函数,请访问https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019