stl - Expose C++ container iterator to user -
say have class foo
, contains kind of container, vector<bar *> bars
. want allow user iterate through container, want flexible might change different container in future. i'm used java, this
public class foo { list<bar> bars; // may change different collection // user use public iterator<bar> getiter() { return bars.iterator(); // can change without user knowing } }
c++ iterators designed raw c++ pointers. how equivalent functionality? following, returns beginning , end of collection iterator user can walk himself.
class foo { vector<bar *> bars; public: // user use std::pair<vector<bar *>::iterator , vector<bar *>::iterator > getiter() { return std::make_pair(bars.begin(), bars.end()); } }
it works, feel must doing wrong.
function declaration exposes fact i'm using
vector
. if change implementation, need change function declaration. not huge deal kind of goes against encapsulation.instead of returning java-like iterator class can own bounds check, need return both
.begin()
,.end()
of collection. seems bit ugly.
should write own iterator class?
you adapt vector behaviour , provide same interface:
class foo { std::vector<bar *> bars; public: typedef std::vector<bar*>::iterator iterator; iterator begin() { return bars.begin(); } iterator end() { return bars.end(); } };
use foo::iterator
iterator type outside of container.
however, bear in mind hiding behind typedef offers less seems. can swap internal implementation long provides same guarantees. example, if treat foo::iterator
random access iterator, cannot swap vector list internally @ later date without comprehensive refactoring because list iterators not random access.
you refer scott meyers effective stl, item 2: beware illusion of container independent code comprehensive argument why might bad idea assume can change underlying container @ point in future. 1 of more serious points iterator invalidation. treat iterators bi-directional, swap vector list @ point. insertion in middle of vector invalidate of iterators, while same not hold list. in end, implementation details leak, , trying hide them might sisyphus work...
Comments
Post a Comment