How do I explicitly initialize a structure's member vector? [duplicate]
Possible Duplicate:
how-to initialize 'const std::vector<T>' like a c array
What's the proper syntax to provide an explicit initializer for a std::vector when it's a member of a structure? Here's the structure:
struct pattern_info
{
std::string pattern;
std::vector<std::string> patterns;
};
Here's how I would like to initialize it (the ??? is the part I'm not sure about):
pattern_info p = { "", ??? };
I know that {} will provide a reasonable default for all the structure members, but I prefer not to do that.
When I compile with -std=c++0x I can do this (and it seems to work):
开发者_高级运维pattern_info p = { "", {} };
I'm using gcc version 4.4.5 (Debian 4.4.5-8) and would like to do this without the -std=c++0x option.
Only C++ 0x's std::vector
has such initializers. In current C++, you have to use an existing vector, like this ...
std::vector<T> foo;
...push_back...push...push...
const std::vector<T> target = foo;
... or use workarounds like boost::assign
.
A second alternative is to use one of std::vector
's alternative constructors. One of them is a template and takes an input-iterator range:
const int foo[] = { 1, 1, 2, 3, 5, 8, 13 };
const std::vector<int> bar (foo,
foo + (sizeof foo / sizeof *foo));
This is only possible in C++0x, as already stated. As an alternative, you could use Boost. Take a look at the example given in the introduction:
> http://www.boost.org/doc/libs/1_39_0/libs/assign/doc/#intro
If vector
is going to be empty (as shown in your c++0x example version) then,
pattern_info p = { "" };
I think, you can even skip to put ""
for std::string
too. If you want non-empty string then only initialize. To get rid of compiler warning, you may try:
pattern_info p = {};
Edit: If you want to get away with the warnings then provide a default constructor.
struct pattern_info
{
//...
pattern_info() : pattern(""), patterns(0) {}
};
And declare as it is:
pattern_info p;
精彩评论