manolo
manolo

Reputation: 71

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!

Upvotes: 2

Views: 76

Answers (1)

Jarod42
Jarod42

Reputation: 217135

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; });
}

Upvotes: 1

Related Questions