Initialize a vector array of strings
C++StlC++ 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<>
:
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