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 :)
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:
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With