Reputation: 119
I'm learning how to use C++ STL and algorithms. Currently, I want to iterate a list of the pointer of objects. This is my approach so far:
for (list<Course*>::iterator it = this->course_list.begin();
it != this->course_list.end(); ++it){
cout<<it->course_code<<endl;
}
this is a method inside a class, course_list
is a member of it and it's a list of the pointer of another class called Course. By doing this, I think "it" now is the pointer to each Course object in the list. course_code
is a member of the class Course.
I tried
it.course_code;
or
it->course_code;
both didn't work.
How do I access the course_code
with "it"?
Thanks for help.
Upvotes: 0
Views: 1396
Reputation: 86
So the iterator functions as a pointer to the underlying data. Meaning lets say I had a vector of integers like below
vector<int> test = {1, 2, 3, 4, 5};
for(auto it = test.begin(); it != test.end()l ++it){
cout << *it << endl;
}
This will do what you desire, you basically need to dereference the iterator to get to the underlying data. So in your case to access the course_code replace
cout<<it->course_code<<endl;
With
cout<<*it<< endl;
Upvotes: 1