Should I write iterators for a class that is just a wrapper for a vector?

Should I write iterators for a class that is just a wrapper for a vector?

The only private member of my class called Record is a vector.

I want to be able to do this:

for (auto& elem : record) {
    // do something with elem
}

where the record is of type Record. To do this, I need to implement iterators for the Record class. But I can do it too:

for (auto& elem : record.elems) {
    // do something with elem
}

where record.elems is the vector I mentioned. But so I will need to make it publicly available.

Another approach:

for (auto& elem : record.getElems()) {
    // do something with elem
}

This way I get the iteration and the member remains private. This is probably the best way to go.

My main question is: why should I try to implement iterators for the Record class when it's just a wrapper for a vector? My colleague insists that I implement iterators, and he cannot even explain to me why this is simply stupid.

+4
2

. , .

. typedef inline begin() end() .

: :

template <class T>
class vectorWrapper
{
  typedef typename std::vector<T> backingType;
  backingType v;
public:
  typedef typename backingType::iterator iterator;
  typedef typename backingType::const_iterator const_iterator;
  iterator begin() { return v.begin(); }
  const_iterator begin() const { return v.begin(); }
  const_iterator cbegin() const { return v.cbegin(); } // C++11
  iterator end() { return v.end(); }
  const_iterator end() const { return v.end(); }
  const_iterator cend() const { return v.cend(); } // C++11
};

( ) reverse_iterator . , , , .

+9

, begin() end(). , : , , : , , . , , , ?

, , , - . , . .

+2

All Articles