solti solti - 8 days ago 6
C++ Question

What is wrong with using struct for pushing multiple types in std::vector?

I am trying to push multiple types into same

std::vector
. For example lets say I want to push
class type1
and
class type2
into a vector.

So basically I would be able to do:

vec.push_back(new type1, new type2);
vec.push_back(new type1, new type2);


What I have in mind is to make type1 and type2 of same type by making them inherit from parent class type (but I don't have this luxury for now).

So I resort to using
struct
. So what I did was

struct type{
type1* t1;
type2* t2;
};
std::vector<type> vec;
vec.push_back({new type1, new type2});


Do you think using struct for this is a good idea or should I use the technique that this post is suggesting? My another question regarding that post why make this complex and not use just
struct
like I did?

Edit: Another way is also to use
std::vector<std::pair <type1, type2>>
but since I might have type3 too so this still won't work for me.

Edit The
type1
and
type2
that I am talking about is
point
and
triangle
.

Edit Answer From Martin : I am now planning to tuple with combining with enum see this for more detail.

Answer

It is a good idea, although you are not profiting from polymorphism. I understand you cannot change type1 and type2 classes, but you can wrap a class around them that suits your need:

(not tested)

class TypeWrap
{
public:
    virtual void execute() = 0;
};

class Type1Wrap : public TypeWrap
{
private:
    Type1 m_type;
public:
    void execute(){ m_type.execute(); }
};

class Type2Wrap : public TypeWrap
{
private:
    Type2 m_type;
public:
    void execute(){ m_type.execute(); }
};

And then use a vector<TypeWrap*> m_types which will allow you to call m_types[0]->execute();

As a side note its bad practice (in a general sense) to use new operators directly, other options such as unique_ptr or shared_ptr are better if you need to allocate dynamically, or simply use Type1Wrap type; m_types.push_back(&type); to get a pointer to the object, but make sure to keep the object alive!

Comments