简体   繁体   English

如何在 C++ 中重新实现包含 STL 指针容器的类的迭代器

[英]How to reimplement iterator of a class that contains STL container of pointers in C++

I have a class that contains a vector of pointers to another class:我有一个包含指向另一个类的指针向量的类:

class B {};

class A {
    std::vector<B*> data_;
};

and I want to provide the user with an iterator.我想为用户提供一个迭代器。 I thought on using a typedef std::vector<B*>::iterator iterator inside the class but that comes with the problem that iterator::operator*() returns a B* and I want it to completely hide the internal representation to the user.我考虑过在类中使用typedef std::vector<B*>::iterator iterator ,但这会带来iterator::operator*()返回B*的问题,我希望它完全隐藏内部表示用户。

I did not find a way to reimplement the operator* and it has occured to me that maybe the only solution is to nest a class with an iternal reference to the STL iterator:我没有找到重新实现operator*的方法,我突然想到,也许唯一的解决方案是嵌套一个带有对 STL 迭代器的内部引用的类:

class B {};

class A {
    std::vector<B*> data_;
    class iterator {
        std::vector<B*>::iterator it;
        B& operator*();
        ...
    };
};

But I wanted to know, is there any other way that is more elegant in order to acomplish this?但我想知道,有没有其他更优雅的方法来完成这个? My approach implies reimplementing all member functions just to call the equivalent ones in std::vector<>::iterator , except for the already mentioned operator.我的方法意味着重新实现所有成员函数只是为了调用std::vector<>::iterator中的等效函数,除了已经提到的运算符。

Thanks!谢谢!

With C++20 ranges, you might do something like:对于 C++20 范围,您可以执行以下操作:

auto bView() /*const*/ {
    return data_
        | std::views::filter([](auto* p){ return p != nullptr; })
        | std::views::transform([](auto* p) -> decltype(auto) { return *p; });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM