views:

659

answers:

3

I'm writing some code against a C++ API that takes vectors of vectors of vectors, and it's getting tedious to write code like the following all over the place:

vector<string> vs1;
vs1.push_back("x");
vs1.push_back("y");
...
vector<string> vs2;
...
vector<vector<string> > vvs1;
vvs1.push_back(vs1);
vvs1.push_back(vs2);
...
vector<vector<string> > vvs2;
...
vector<vector<vector<string> > > vvvs;
vvvs.push_back(vvs1);
vvvs.push_back(vvs2);
...

Does C++ have a vector literal syntax? I.e., something like:

vector<vector<vector<string>>> vvvs = 
    { { {"x","y", ... }, ... }, ... }

Is there a non-builtin way to accomplish this?

+17  A: 

In C++0x you will be able to use your desired syntax:

vector<vector<vector<string> > > vvvs = 
    { { {"x","y", ... }, ... }, ... };

But in today's C++ you are limited to using boost.assign which lets you do:

vector<string> vs1;
vs1 += "x", "y", ...;
vector<string> vs2;
...
vector<vector<string> > vvs1;
vvs1 += vs1, vs2, ...;
vector<vector<string> > vvs2;
...
vector<vector<vector<string> > > vvvs;
vvvs += vvs1, vvs2, ...;

... or using Qt's containers which let you do it in one go:

QVector<QVector<QVector<string> > > vvvs =
    QVector<QVector<QVector<string> > >() << (
        QVector<QVector<string> >() << (
            QVector<string>() << "x", "y", ...) <<
            ... ) <<
        ...
    ;

The other semi-sane option, at least for flat vectors, is to construct from an array:

string a[] = { "x", "y", "z" };
vector<string> vec(a, a + 3);
I would recommend using an automated way of retrieving the array size, as the one posted by litb here: http://stackoverflow.com/questions/437150/can-someone-explain-this-template-code-that-gives-me-the-size-of-an-array
David Rodríguez - dribeas
Yep sure. Didnt wanna complicate the answer.
+4  A: 

Check out Boost assign library.

Fred Larson
+3  A: 

Basically, there's no built-in syntax to do it, because C++ doesn't know about vectors ether; they're just from a convenient library.

That said, if you're loading up a complicated data structure, you should load it from a file or something similar anyway; the code is too brittle otherwise.

Charlie Martin
not only should such a structure not be hardcoded, but I think the fact that such nested vectors are being manipulated directly is a code smell... there should probably be a class encapsulating some or all of that.
rmeador