c++ - 如何从 C++ 中的另一个类迭代获取数据?

标签 c++ iterator

在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.

(并假设想要打印元素只是一些其他复杂操作的占位符)

您仍然可以通过 typedefA 公开您的 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/

相关文章:

c++ - Boost 目录迭代器 "no such file or directory"

ruby - "each"、 "foreach"、 "collect"和 "map"之间有什么区别?

c++ - 为什么要使用 QStringLiteral?

c++ - QDockWidget 可拖动标签

c++ - 链表类的复制构造函数

c++ - 在 Linux 上静态链接库

c++ - 从文件中读取并有效地将单词添加到树中

c++ - 使用 C++ std::list 迭代器替换列表中的项目

php - 为没有容器数组的 ArrayAccess 实现 Iterator 接口(interface)

c++ - 为什么设置迭代器指针会导致段错误?