C ++中的异构容器 [英] Heterogeneous containers in C++

查看:153
本文介绍了C ++中的异构容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个漂亮的图形,它根据不同的数据需求分类哪个STL容器,如:

I saw this nice graphic which classifies which STL container would suit based on different requirements of data such as:

- 固定大小Vs变量大小

-- Fixed Size Vs Variable size

- 相同类型的数据与不同类型的数据

-- Data of same tyme Vs different type

- 排序与未排序的数据

-- Sorted Vs unsorted data

- 顺序与随机存取

-- Sequential Vs random access

http:/ /plasmahh.projectiwear.org/cce_clean.svg

我注意到那张图片,C ++ STL没有容器

I notice in that image, that C++ STL there is no container which is


  1. 变量大小

  2. 异质(不同类型的数据)。

不是C ++有这样的东西吗?

Doesn't C++ have something for this?

推荐答案

很好的一般情况下, C ++容器设计为使用模板保存单个类型的对象。如果你想要不同类型的所有派生自一个类型,你可以存储一个指针的容器(我想你也可以有一个容器void *任何东西...)。 std :: vector< MyBaseType *>。

Well generally C++ Containers are designed to hold objects of a single type using templates. If you want different types that are all derived from one type you can store a container of pointers (I guess you could also have a container of void* to anything...) e.g. std::vector<MyBaseType*>.

如果你想要完全不相关的类型,你可以存储可以安全地引用其他类型的对象,例如boost :: any 。

If you want completely unrelated types, you can store objects that can safely reference those other types, such as boost::any.

http:// www.boost.org/doc/libs/1_47_0/doc/html/any.html

关于boost网站的一些示例:

Some examples off the boost site:

#include <list>
#include <boost/any.hpp>

using boost::any_cast;
typedef std::list<boost::any> many;

void append_int(many & values, int value)
{
    boost::any to_append = value;
    values.push_back(to_append);
}

void append_string(many & values, const std::string & value)
{
    values.push_back(value);
}

bool is_int(const boost::any & operand)
{
    return operand.type() == typeid(int);
}
bool is_char_ptr(const boost::any & operand)
{
    try
    {
        any_cast<const char *>(operand);
        return true;
    }
    catch(const boost::bad_any_cast &)
    {
        return false;
    }
}

boost :: variant类似,允许的类型,而不允许您容器中的任何类型。

boost::variant is similar, but you specify all the allowed types, rather than allowing any type in your container.

http://www.boost.org/doc/libs/1_47_0/doc/html/variant.html

std::vector< boost::variant<unsigned, std::string> > vec;
vec.push_back( 44);
vec.push_back( "str" );
vec.push_back( SomthingElse(55, 65) ); //not allowed

这篇关于C ++中的异构容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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