如何遍历 C++ 中的对象指针列表
How to iterate through a list of the pointers of objects in C++
我正在学习如何使用 C++ STL 和算法。
目前,我想迭代一个对象指针列表。
到目前为止,这是我的方法:
for (list<Course*>::iterator it = this->course_list.begin();
it != this->course_list.end(); ++it){
cout<<it->course_code<<endl;
}
这是 class 中的一个方法,course_list
是其中的一个成员,它是另一个 class 的指针列表,称为 Course。通过这样做,我认为“它”现在是指向列表中每个 Course 对象的指针。 course_code
是 class 课程的成员。
我试过了
it.course_code;
或
it->course_code;
两者均无效。
如何使用“它”访问 course_code
?
感谢您的帮助。
所以迭代器充当指向基础数据的指针。意思是说我有一个整数向量,如下所示
vector<int> test = {1, 2, 3, 4, 5};
for(auto it = test.begin(); it != test.end()l ++it){
cout << *it << endl;
}
这会如您所愿,您基本上需要取消对迭代器的引用以获取基础数据。所以在你的情况下访问 course_code replace
cout<<it->course_code<<endl;
有
cout<<*it<< endl;
我正在学习如何使用 C++ STL 和算法。 目前,我想迭代一个对象指针列表。 到目前为止,这是我的方法:
for (list<Course*>::iterator it = this->course_list.begin();
it != this->course_list.end(); ++it){
cout<<it->course_code<<endl;
}
这是 class 中的一个方法,course_list
是其中的一个成员,它是另一个 class 的指针列表,称为 Course。通过这样做,我认为“它”现在是指向列表中每个 Course 对象的指针。 course_code
是 class 课程的成员。
我试过了
it.course_code;
或
it->course_code;
两者均无效。
如何使用“它”访问 course_code
?
感谢您的帮助。
所以迭代器充当指向基础数据的指针。意思是说我有一个整数向量,如下所示
vector<int> test = {1, 2, 3, 4, 5};
for(auto it = test.begin(); it != test.end()l ++it){
cout << *it << endl;
}
这会如您所愿,您基本上需要取消对迭代器的引用以获取基础数据。所以在你的情况下访问 course_code replace
cout<<it->course_code<<endl;
有
cout<<*it<< endl;