Generating a vector with int and string arguments

让人想犯罪 __ 提交于 2019-12-25 18:29:36

问题


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.

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


回答1:


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"));

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

Since you're probably iterating, a visitor will likely work better. You create a functor that has overloads for each type in your variant, and use boost::apply_visitor. For example:

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



回答2:


You could create a vector of Strings and then use .toString() in the positions with numbers. Or at least in Java you could create a Class VectorIntString that every instance of the class has both vectors. So when you construct the object: you will do something like this

VectorIntString vec= new VectorIntString(int a,String a, int b, String b.... ,);

So the constructor will add odds position to the Int vector and even positions to the String vector.



来源:https://stackoverflow.com/questions/36183070/generating-a-vector-with-int-and-string-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!