Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL iterator as return value

Tags:

c++

iterator

stl

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 :)

like image 229
user44986 Avatar asked Dec 29 '22 10:12

user44986


2 Answers

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:
}
like image 84
Bill Avatar answered Jan 11 '23 13:01

Bill


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.

like image 28
David Thornley Avatar answered Jan 11 '23 14:01

David Thornley