How to define a custom iterator in C++

Posted by Robert Martin on Stack Overflow See other posts from Stack Overflow or by Robert Martin
Published on 2012-11-20T21:28:20Z Indexed on 2012/11/20 23:01 UTC
Read the original article Hit count: 124

Filed under:
|

I've seen a number of posts on SO about how to define custom iterators, but nothing that seems to exactly answers my question, which is...

How do I create an iterator that hides a nested for loop?

For instance, I have a class Foo, inside of the Foo is a Bar, and inside of the Bar is a string. I could write

for (const Foo& foo : foo_set)
  for (const Bar& bar : foo.bar_set)
    if (bar.my_string != "baz")
      cout << bar.my_string << endl;

but instead I want to be able to do something like:

for (const string& good : foo_set)
  cout << good << endl;

How do I do something like this?

© Stack Overflow or respective owner

Related posts about c++

Related posts about iterator