jeudi 19 septembre 2019

Can I initialise a std::vector

I have some objects like this:

Obj o1{};
Obj o2{};
Obj o3{};
...

However, I also have another class Foo which has a std::vector<Obj*> as a member.

How can I initialise the vector from an arbitrary list?

I would like to construct Foo like this:

Foo f{o1, o3, o4};

I have tried this knowing that I can't have collections of references.

    class Foo {
    public:
        explicit Foo(std::initializer_list<Obj&> px) {
            for (auto& p : px) {
                fwds.push_back(&p);
            }
        }

        ...

    private:
        std::vector<Obj*> fwds;
    };

Aucun commentaire:

Enregistrer un commentaire