How to get a vector of different vectors in C++

2019-03-03 08:56发布

问题:

I'd like to have a C++ representation of a table like the following:

0   1   2
=   =   =
1  1.0  a
2  2.0  b
3  3.0  c

The types of the columns have to be chosen from int, double or string at runtime.

What is the best way to express it in C++?

Addendum: my real problem: I want a columnar representation of a database table which can have arbitrary SQL types (I'll settle for int, double and string).

回答1:

edit: to create an object of dynamic type at runtime, google "factory pattern".

You need the first vector to contain a consistent type, so you probably (in C++) want to have a base class and derive from it. I'm not sure if the std::vector class has an untyped base (it might).

So, you either create a wrapper class around the concept of a vector (yuck), you create a vector of variant types (yuck), or you create a some kind of variant vector (yuck). I'd probably choose the latter because its the simplest method that still has type safe vectors within it.

typedef union VectorOfThings {
    std::vector<int> i;
    std::vector<double> d;
    std::vector<string> s;
};
struct TypedVectorOfThings {
    enum Type { ints, doubles, strings };
    Type type;
    VectorOfThings myVector;
};
std::vector<TypedVectorOfThings > myVectorOfVectors;

and season to taste. But oh dear gods it's horrible. Is this a run time representation of a user defined database table or something?



回答2:

Probably with a record/row class:

struct Record
{
    int col1;
    double col2;
    string col3;
}

std::vector<Record> records;


标签: c++ vector stl