在 std::vector 中使用结构来推送多个类型有什么问题?

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

本文关键字:类型 什么 问题 vector std 结构      更新时间:2023-10-16

>我正在尝试将多个类型推入同一个std::vector。例如,假设我想将class type1class type2推送到向量中。

所以基本上我能够做到:

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

我想到的是,通过使它们从父类类型继承来使 type1 和 type2 具有相同的类型(但我现在没有这种奢侈)。

所以我求助于使用struct.所以我所做的是

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

您认为为此使用结构是一个好主意还是我应该使用这篇文章建议的技术?我关于该帖子的另一个问题,为什么要让它变得复杂而不是像我一样只使用struct

编辑:另一种方法是使用std::vector<std::pair <type1, type2>>但是由于我可能也有type3,因此这仍然对我不起作用。

编辑我所说的type1type2pointtriangle

评论部分编辑马丁的答案:我现在计划使用tuple with combining with enum查看更多详细信息。

注释中的具体答案:then you could template it to the types using std::tuple instead of std::pair, as std::vector<std::tuple<type1, type2,.. typen>> m_types


这是一个好主意,尽管您没有从多态性中获利。我知道您不能更改 type1 和 type2 类,但您可以围绕它们包装一个适合您需求的类:

(未测试)

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

然后使用允许您调用m_types[0]->execute();vector<TypeWrap*> m_types

作为旁注,直接使用新运算符的不良做法(在一般意义上),如果您需要动态分配,或者只是使用Type1Wrap type; m_types.push_back(&type);来获取指向对象的指针,则其他选项(如 unique_ptr 或 shared_ptr)更好,但请确保保持对象处于活动状态!