在A类中,有一个 vector V。 V 是私有(private)成员。
在 B 类中,我想打印 V 的所有项目。 执行此操作的最佳方法是什么?
在同一个类中很容易得到一个 vector 的迭代器,但在另一个类中就不容易了。
感谢阅读。
最佳答案
接受你的观点:
It is very easy to get an iterator of a vector in the same class, but not easy in another class.
(并假设想要打印元素只是一些其他复杂操作的占位符)
您仍然可以通过 typedef
从 A
公开您的 vector 的迭代器,它可以在 B
内部使用,例如
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();
}
};
然后你可以像这样使用这些迭代器:
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, " "));
}
};
在这种情况下,我使用了 const_iterator
,因为您要求的是只读访问权限,但如果您需要写访问权限,则可以使用 iterator
代替(尽管这很可能是一个糟糕的设计选择,写信给这样的内部成员)。
关于c++ - 如何从 C++ 中的另一个类迭代获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1367311/