Taking your point:
It is very easy to get an iterator of
a vector in the same class, but not
easy in another class.
(and assuming that wanting to print the elements is a just a place holder for some other complicated action)
You can still expose the an iterator for your vector from A
that can be used inside of B
via a typedef
, e.g.
class A
{
private:
std::vector<int> V;
public:
typedef std::vector<int>::const_iterator const_iterator;
const const_iterator begin() const
{
return V.begin();
}
const const_iterator end() const
{
return V.end();
}
};
Then you can use those iterators like this:
class B
{
public:
void Foo()
{
A a;
// do stuff that will put things into the collection inside 'a'
std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, " "));
}
};
I've used const_iterator
in this case, because you asked for read-only access, but you can use iterator
instead if you need write access (although that's likely to be a poor design choice, writing to an internal member like that).