是否可以初始化字符串的向量数组.
例如:
static std::vector<std::string> v; //声明为类成员
我static只是用来初始化并用字符串填充它.或者我应该在构造函数中填充它,如果它不像我们常规数组那样初始化.
Ste*_*sop 63
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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
小智 31
如果您正在使用cpp11(-std=c++0x如果需要,可以使用标志启用),那么您可以像这样简单地初始化向量:
// static std::vector<std::string> v;
v = {"haha", "hehe"};
Run Code Online (Sandbox Code Playgroud)
All*_*leo 30
这是2017年,但是这个帖子在我的搜索引擎中排名第一,今天首选以下方法(初始化列表)
std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
std::vector<std::string> v({ "xyzzy", "plugh", "abracadabra" });
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" };
Run Code Online (Sandbox Code Playgroud)
来自https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists
Moo*_*ice 15
const char* args[] = {"01", "02", "03", "04"};
std::vector<std::string> v(args, args + 4);
Run Code Online (Sandbox Code Playgroud)
在C++ 0x中,您可以利用std::initializer_list<>:
http://en.wikipedia.org/wiki/C%2B%2B0x#Initializer_lists
Tom*_*Tom 10
MSVC 2010解决方案,因为它不支持std::initializer_list<>向量,但它确实支持std::end
const char *args[] = {"hello", "world!"};
std::vector<std::string> v(args, std::end(args));
Run Code Online (Sandbox Code Playgroud)
和@ Moo-Juice一样:
const char* args[] = {"01", "02", "03", "04"};
std::vector<std::string> v(args, args + sizeof(args)/sizeof(args[0])); //get array size
Run Code Online (Sandbox Code Playgroud)