C ++通用向量 [英] C++ Generic Vector

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

问题描述

在c ++中是否可以创建多个类型的向量?我想能够构建和迭代包含许多不同类型的矢量。例如:

Is it possible in c++ to create a vector of multiple types? I'd like to be able to build and iterate over a vector that contains many different types. For example:

vector<generic> myVec;
myVec.push_back(myInt);
myVec.push_back(myString);
etc...

向量需要能够保存不同的数据类型。是否还有另一个向量类型,我应该在c ++库中使用?

The vector needs to be able to hold differing data types. Is there another vector-like type I should be using in the c++ library?

任何方向都可以使用。

推荐答案

您可以使用 boost :: any 。例如:

You could use boost::any. For instance:

#include <vector>
#include <boost/any.hpp>
#include <iostream>

struct my_class { my_class(int i) : x{i} { } int x; };

int main()
{
    std::vector<boost::any> v;

    v.push_back(42);
    v.push_back(std::string{"Hello!"});
    v.push_back(my_class{1729});

    my_class obj = boost::any_cast<my_class>(v[2]);
    std::cout << obj.x;
}

如果要将允许的类型集限制在某个定义的范围,可以使用 boost :: variant

If you want to restrict the set of allowed types to some defined range, you could use boost::variant instead:

#include <vector>
#include <boost/variant.hpp>
#include <iostream>

struct my_class { my_class(int i) : x{i} { } int x; };

int main()
{
    typedef boost::variant<int, std::string, my_class> my_variant;
    std::vector<my_variant> v;

    v.push_back(42);
    v.push_back("Hello!");
    v.push_back(my_class{1729});

    my_class obj = boost::get<my_class>(v[2]);
    std::cout << obj.x;
}

boost :: variant 也支持访问。您可以定义一个可以处理变体中所有可能类型的访问者:

boost::variant also supports visiting. You could define a visitor that can handle all the possible types in the variant:

struct my_visitor : boost::static_visitor<void>
{
    void operator () (int i)
    {
        std::cout << "Look, I got an int! " << i << std::endl;
    }

    void operator () (std::string const& s)
    {
        std::cout << "Look, I got an string! " << s << std::endl;
    }

    void operator () (my_class const& obj)
    {
        std::cout << "Look, I got a UDT! And inside it a " << obj.x << std::endl;
    }
};

然后按如下方式调用它:

And then invoke it as done below:

int main()
{
    typedef boost::variant<int, std::string, my_class> my_variant;
    std::vector<my_variant> v;

    v.push_back(42);
    v.push_back("Hello!");
    v.push_back(my_class{1729});

    my_visitor mv;
    for (auto const& e : v)
    {
        e.apply_visitor(mv);
    }
}

这里是 生活示例 boost :: variant 的好处是它将执行编译时检查,以确保您的访问者可以处理该变体可以容纳的所有类型。

Here is a live example. The nice thing about boost::variant is that it will perform a compile-time check to make sure that your visitor can handle all the types that the variant can hold.

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

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