STL iterator as return value

10,814

Solution 1

Why not add both a begin() and end() function to your class that simply return v.begin(); and return v.end();? (Assuming v is your vector.)

class MyVectorWrapper
{
public:
  // Give yourself the freedom to change underlying types later on:
  typedef vector<int>::const_iterator const_iterator;

  // Since you only want to read, only provide the const versions of begin/end:
  const_iterator begin() const { return v.begin(); }
  const_iterator end() const { return v.end(); }

private:
  // the underlying vector:
  vector<int> v;
}

Then you could iterate through your class like any other:

MyVectorWrapper myV;
for (MyVectorWrapper::const_iterator iter = myV.begin(); iter != myV.end(); ++i)
{
  // do something with iter:
}

Solution 2

It seems potentially unwise to give that much access to the vector, but if you're going to why not just return a pointer or reference to the vector? (Returning the vector itself is going to be potentially expensive.) Alternately, return a std::pair<> of iterators.

An iterator is just an indicator for one object; for example, a pointer can be a perfectly good random-access iterator. It doesn't carry information about what sort of container the object is in.

Solution 3

The STL introduced the idiom of using two iterators for describing a range. Since then begin() and end() are the getters. The advantage of this is that a simple pair of pointers into a C array can be used as perfect iterators. The disadvantage is that you need to carry around two objects. C++1x will, AFAIK, introduce a range concept to somewhat ease the latter.

Share:
10,814
user44986
Author by

user44986

Updated on June 04, 2022

Comments

  • user44986
    user44986 almost 2 years

    I have class A, that contains std::vector and I would like to give an access to the vector from outside class A.

    The first thing that came to my mind is to make a get function that returns iterator to the vector, but walk through the vector I will need two iterators (begin and end).

    I was wondering is there any way (technique or patters) to iterate whole vector with only one iterator? Or maybe some other way to get access to vector, of course without using vector as return value :)