C++ 初始化字符串向量数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4268886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize a vector array of strings
提问by cpx
Would it be possible to initialize a vector array of strings.
是否可以初始化字符串的向量数组。
for example:
例如:
static std::vector<std::string> v;
//declared as a class member
static std::vector<std::string> v;
//声明为类成员
I used static
just to initialize and fill it with strings. Or should i just fill it in constructor if it can't be initialized like we do regular arrays.
我曾经static
只是初始化并用字符串填充它。或者如果它不能像我们做常规数组那样初始化,我应该在构造函数中填充它。
采纳答案by Steve Jessop
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:
end
只是这样我就不必编写vinit+3
并在以后长度发生变化时保持最新状态。将其定义为:
template<typename T, size_t N>
T * end(T (&ra)[N]) {
return ra + N;
}
回答by Alleo
It is 2017, but this thread is top in my search engine, today the following methods are preferred (initializer lists)
现在是 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" };
From https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists
回答by Yunqing Gong
If you are using cpp11 (enable with the -std=c++0x
flag if needed), then you can simply initialize the vector like this:
如果您使用的是 cpp11(-std=c++0x
如果需要,使用标志启用),那么您可以简单地初始化向量,如下所示:
// static std::vector<std::string> v;
v = {"haha", "hehe"};
回答by Moo-Juice
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<>
:
在 C++0x 中,您可以利用std::initializer_list<>
:
回答by Tom
MSVC 2010 solution, since it doesn't support std::initializer_list<>
for vectors but it does support std::end
MSVC 2010 解决方案,因为它不支持std::initializer_list<>
向量但它支持std::end
const char *args[] = {"hello", "world!"};
std::vector<std::string> v(args, std::end(args));
回答by Mark Kahn
same as @Moo-Juice:
与@Moo-Juice 相同:
const char* args[] = {"01", "02", "03", "04"};
std::vector<std::string> v(args, args + sizeof(args)/sizeof(args[0])); //get array size
回答by Nikolai Fetissov
Take a look at boost::assign
.
回答by David
In C++0x you will be able to initialize containers just like arrays
在 C++0x 中,您将能够像数组一样初始化容器