How to declare an array of strings in C++?


I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?

Possible non-solutions:

vector<string> v;

for(int i = 0; i < v.size(); i++)
    cout << v[i] << endl;

Problems - no way to create the vector on one line with a list of strings

Possible non-solution 2:

string list[] = {"abc", "xyz"};

Problems - no way to get the number of strings automatically (that I know of).

There must be an easy way of doing this.

12/22/2015 7:18:47 PM

Accepted Answer

The boost assign library seems to be exactly what you are looking for. It makes assigning constants to containers easier than ever.

8/29/2008 6:44:08 PM

C++ 11 added initialization lists to allow the following syntax:

std::vector<std::string> v = {"Hello", "World"};

Support for this C++ 11 feature was added in at least GCC 4.4 and only in Visual Studio 2013.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow