Initialize a vector array of strings

C++Stl

C++ Problem Overview


Would it be possible to initialize a vector array of strings?

for example:

static std::vector<std::string> v; //declared as a class member

I used static just to initialize and fill it with strings. Or should i just fill it in the constructor if it can't be initialized like we do with regular arrays.

C++ Solutions


Solution 1 - C++

It is 2017, but this thread is top in my search engine, today the following methods are preferred (initializer lists)

std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
std::vector<std::string> v({ "xyzzy", "plugh", "abracadabra" });
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" }; 

From https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists

Solution 2 - C++

Sort of:

class some_class {
    static std::vector<std::string> v; // declaration
};

const char *vinit[] = {"one", "two", "three"};

std::vector<std::string> some_class::v(vinit, end(vinit)); // definition

end is just so I don't have to write vinit+3 and keep it up to date if the length changes later. Define it as:

template<typename T, size_t N>
T * end(T (&ra)[N]) {
    return ra + N;
}

Solution 3 - C++

If you are using cpp11 (enable with the -std=c++0x flag if needed), then you can simply initialize the vector like this:

// static std::vector<std::string> v;
v = {"haha", "hehe"};

Solution 4 - C++

 const char* args[] = {"01", "02", "03", "04"};
 std::vector<std::string> v(args, args + 4);

And in C++0x, you can take advantage of std::initializer_list<>:

http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists

Solution 5 - C++

MSVC 2010 solution, since it doesn't support std::initializer_list<> for vectors but it does support std::end

const char *args[] = {"hello", "world!"};
std::vector<std::string> v(args, std::end(args));

Solution 6 - C++

same as @Moo-Juice:

const char* args[] = {"01", "02", "03", "04"};
std::vector<std::string> v(args, args + sizeof(args)/sizeof(args[0])); //get array size

Solution 7 - C++

Take a look at boost::assign.

Solution 8 - C++

In C++0x you will be able to initialize containers just like arrays

http://www2.research.att.com/~bs/C++0xFAQ.html#init-list

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncpxView Question on Stackoverflow
Solution 1 - C++AlleoView Answer on Stackoverflow
Solution 2 - C++Steve JessopView Answer on Stackoverflow
Solution 3 - C++Yunqing GongView Answer on Stackoverflow
Solution 4 - C++Moo-JuiceView Answer on Stackoverflow
Solution 5 - C++TomView Answer on Stackoverflow
Solution 6 - C++Mark KahnView Answer on Stackoverflow
Solution 7 - C++Nikolai FetissovView Answer on Stackoverflow
Solution 8 - C++DavidView Answer on Stackoverflow