Quick Q: How do I allow iteration on an internal vector without exposing the vector?—StackExchange

Save to:
Instapaper Pocket Readability

Quick A: By exposing wrapped iterators in your interface.

From Programmers StackExchange, StackOverflow's sister site:

Allow iteration of an internal vector without leaking the implementation

I have a class that represents a list of people.

class AddressBook

  std::vector<People> people;
I want to allow clients to iterate over the vector of people. The first thought I had was simply:
std::vector<People> & getPeople { return people; }
However, I do not want to leak the implementation details to the client. I may want to maintain certain invariants when the vector is modified, and I lose control over these invariants when I leak the implementation.
What's the best way to allow iteration without leaking the internals?

Add a Comment

You must sign in or register to add a comment.

Comments (1)

0 0

Gvidon said on Dec 9, 2014 02:41 AM:

What about a simple for_each member function?

struct S
template<typename Func>
void for_each(Func f)
for (const auto &i: m_vec)

std::vector<int> m_vec;

Details may vary, of course