Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector literals, or something like them

People also ask

What is similar to vector C++?

Software Engineering C++ In this article, we have explored the alternatives of Vector in C++ such as: array. Deque. Linked List.

Is vector faster than set C++?

The time complexity for the insertion of a new element is O(log N). Vector is faster for insertion and deletion of elements at the end of the container. Set is faster for insertion and deletion of elements at the middle of the container.

What is a string literal C++?

String literals. A string literal represents a sequence of characters that together form a null-terminated string. The characters must be enclosed between double quotation marks.

Can a vector store different data types?

ORIGINAL ANSWER: The easiest way to store multiple types in the same vector is to make them subtypes of a parent class, wrapping your desired types in classes if they aren't classes already.


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

Check out Boost assign library.


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.