如何将不同类型的对象存储在C ++容器中? [英] How can I store objects of differing types in a C++ container?

查看:675
本文介绍了如何将不同类型的对象存储在C ++容器中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个我可以使用或构建的C ++容器,包含 int string double 类型?我面临的问题是,每当我尝试填充,说,地图,向量或列表,例如,如下:

Is there a C++ container that I could use or build that can contain, say, int and string and double types? The problem I'm facing is that whenever I try to populate, say, a map, vector or list with, say, the following:

int x;
string y;
double z;

我受到格式限制:

list<int> mycountainer;
vector<string> mycontainer;

这会强制 mycontainer 类型

在任何人建议泛型之前,这不会工作,因为标准向量 list 随C ++ 一起提供的容器已经是通用 - 它们可以是任何类型的容器,但不能包含多个类型。

Before anyone suggest generics, that wouldn't work either since the standard vector and list containers that come with C++ are already generic - they can be container for any types but cannot contain multiple types.

我想避免使用Boost,如果可能的话 - 我更喜欢它,如果有一个简单的方法,我可以自己编码这个。

I would like to avoid using Boost also if at all possible - I'd prefer it if there is a simple way I could code this myself.

编辑]
嘿,伙计,非常感谢您的建议 - 我应该解释如何使用这个容器,但它是一个很复杂,因此上面的(大)简化。我认为最好的选择从这里是使用Boost。

[edit] Hey guy, many thanks for your suggestions - I should explain how I'll use this container, but it's a tad complicated hence the (big) simplification above. I think the best option from here is using the Boost. Thanks again.

推荐答案

您可以使用(或重新实现) boost :: any 并在容器中存储 boost :: any 的实例。这将是最安全的,因为 boost :: any 可能处理了在一般情况下解决这类问题涉及的大多数边缘情况和复杂性。

You could use (or re-implement) boost::any and store instances of boost::any in a container. That would be the safest, since boost::any has probably dealt with much of the edge cases and complexity involved in solving this kind of problem in the general case.

如果你想做一些快速和脏的事情,创建一个结构或者一个包含所有潜在类型的成员的联合以及枚举或其他类型为活动的指示符物体。对联合会特别小心,因为它们有一些有趣的属性(例如,如果你读取错误的联合成员,则调用未定义的行为,一次只能有一个成员处于活动状态,即最近写入的成员)。

If you want to do something quick and dirty, create a structure or perhaps a union containing members of all potential types along with an enumeration or other indicator of which type is 'active' in the object. Be especially careful with unions as they have some interesting properties (such as invoking undefined behavior if you read the wrong union member, only one of the members can be 'active' at a time, the one that was most recently written to).

我很好奇你在做什么,你需要这样一个结构。

I'm curious what you're doing that you need such a construct, though.

这篇关于如何将不同类型的对象存储在C ++容器中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆