Reputation: 399
I have a linked list using std::list, that is of custom type "node" (std::list<node>)
which is implemented through
struct node {
std::string pname;
int time;
};
I am wondering how I can create an iterator so that I can loop through my linked list to be able to print out the contents of 'pname' and 'time', or if the creation of a custom iterator is not needed to do so, would like to know how that could be done. Thanks!
Upvotes: 0
Views: 144
Reputation: 48635
It's pretty straightforward. Something a bit like this:
#include <iostream>
#include <list>
struct node {
std::string pname;
int time;
};
int main()
{
std::list<node> nodes {
{"test 1", 1},
{"test 2", 2},
};
for(auto& n: nodes) // range-based for
std::cout << n.pname << ": " << n.time << '\n';
// iterator
for(auto iter = std::begin(nodes); iter != std::end(nodes); ++iter)
std::cout << iter->pname << ": " << iter->time << '\n';
}
Output:
test 1: 1
test 2: 2
test 1: 1
test 2: 2
Upvotes: 2