I am writing a program in which a class has a data member that is a big std::vector
(on the order of 100k - 1M items). Other classes need to be able to access this vector. At the moment I have a standard accessor function that returns the vector, but this returns a copy of the vector I believe. I think it would be more memory and time efficient to just return an iterator or a pointer to the first element. However, if I do this, how can one then use this pointer to run through the vector
and know when to stop (i.e. where the vector ends)?
My code looks like this:
class MyClass
{
private:
std::vector<MyObj> objects_;
//...
public:
std::vector<MyObj> getObjects() { return objects_; }
//...
}
This question arises in another form for me when I want to run through (simulated) concatenated vectors. If I have a vector
of MyClass
, I'd like to be able to iterate over all of the contained object_
vectors. I know from this answer that boost::join does what I have in mind, but I think I need to return copies for it to work. Can I return a pointer to the vector and still retain the ability to iterate over it and others in succession?