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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With