开发者

Initialize a vector array of strings

开发者 https://www.devze.com 2023-01-27 06:47 出处:网络
Would it be possible to initialize a vector array of strings? for example: static std::vector<std::string> v; //declared as a class member

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.


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


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


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


 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


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


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


Take a look at boost::assign.


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消