Say I have a class Foo
, which contains some kind of container, say a vector<Bar *> bars
. I want to allow the user to iterate through this container, but I want to be flexible so that I might change to a different container in the future. I'm used to Java, where I could do this
public class Foo
{
List<Bar> bars; // may change to a different collection
// User would use this
public Iterator<Bar> getIter()
{
return bars.iterator(); // can change without user knowing
}
}
C++ iterators are designed to look like raw C++ pointers. How do I get the equivalent functionality? I could do the following, which returns the beginning and end of the collection as an iterator that the user can walk himself.
class Foo
{
vector<Bar *> bars;
public:
// user would use this
std::pair<vector<Bar *>::iterator , vector<Bar *>::iterator > getIter()
{
return std::make_pair(bars.begin(), bars.end());
}
}
It works, but I feel I must be doing something wrong.
Function declaration exposes the fact that I'm using a
vector
. If I change the implementation, I need to change the function declaration. Not a huge deal but kind of goes against encapsulation.Instead of returning a Java-like iterator class that can do its own bounds check, I need to return both the
.begin()
and.end()
of the collection. Seems a bit ugly.
Should I write my own iterator class?