Initialize a vector array of strings

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.

232291 次浏览

Take a look at boost::assign.

 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

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

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

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

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

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

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"};

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