生成与int和字符串参数向量 [英] Generating a vector with int and string arguments

查看:137
本文介绍了生成与int和字符串参数向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Boost库(增强::变种)在C ++中定义是否整数和字符串的向量。我奋力填补了这样的载体 - 能有人会发布一个例子code。与填充与整数字符串一个vector 使用Boost库的并读取载体或其他元素直接我一个例子。

I would like to use the boost library (boost::variant) in C++ to define a vector if integers and strings. I am struggling to fill a such a vector - can someone either post an example code with fills a vector with ints and strings using the Boost library and reads elements of the vector or otherwise direct me to an example.

我搜索与踏歌的boost ::变种的SO文章,但无法找到我想要的东西。

I searched for articles with the tage boost::variants on the SO, but could not find what I wanted.

推荐答案

下面是一些例子(从内存中写入):

Here are some examples (written from memory):

typedef boost::variant<
   std::string,
   int
> StringOrInt;   // using a typedef is just for convenience

StringOrInt myVariant;
myVariant = std::string("hello");  // both of these work
myVariant = 5;

std::vector<StringOrInt> myvec;
myvec.push_back(5);
myvec.push_back(std::string("hello"));

接着读,有两种方法。一种是使用boost ::得到的,另一种是使用访问者。游客通常更强劲一些,但如果它是一个简单的例子,提振::获得可以很好地工作。

Then to read, there are two ways. One is using boost::get, the other is using a visitor. Visitor is usually a bit more robust, but if it's a simple case, boost::get can work well.

std::string& mystr = boost::get<std::string>(myvec[0]); // this will throw if the type you requested isn't what's stored
std::string* mystr = boost::get<std::string*>(myvec[0]); // pointer version doesn't throw

因为你可能迭代,访客可能会更好地工作。创建具有重载你的变型,各型函子,并使用的boost :: apply_visitor的。例如:

struct MyVisitor {
    void operator()(const std::string& arg) const {
        std::cout << "It was a string";
    }

    void operator()(int arg) const {
        std::cout << "It was an int";
    }
};

MyVisitor myVisitor;
for (auto& val : myvec) {
     boost::apply_visitor(myVisitor, val);
}

这篇关于生成与int和字符串参数向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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