简体   繁体   中英

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.

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:

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.

Thanks!

With C++20 ranges, you might do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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