Reputation: 603
You can create a C++ structure with an array within:
struct foo{
int bar[42];
};
What I would like to do is:
struct foo{
std::vector<int> bar(42);
};
Of course this doesn't compile, but you get the intent. I'm aware of .reserve() and the like,
but I would like to have the space already allocated when declaring a foo
.
The reason is that I'm supposed to alter a rather complicated Perl script which is generating C code with arrays within structs. These arrays should be replaced by std::vector
s. The script subsequently initializes the arrays depending on an XML file and I would rather not mess around with push_back
in the script since the structures are deeply nested (structs of arrays and arrays of structs). The sizes of the arrays do of course vary.
Thanks for your suggestions.
Upvotes: 1
Views: 4816
Reputation: 183
Use constructor, as suggested in other answers. But I must fix you:
Upvotes: 0
Reputation:
The existing answers have explained how to do what you want to do, but I think they've missed the important part of explaining why. The thing that you need to grasp is that struct
in C++ is simply a near-synonym for class
with the only difference being that a struct defaults to having public members and a class defaults to having private. You could replace every instance of class
in your code with
struct X
{
private:
...
}
and it would work exactly the same and vice versa for replacing structs
with class
. This means that just as you would use a constructor to do what you want with a class, you use a constructor with your struct:
struct foo
{
std::vector<int> bar;
foo() : bar(42) {}
}
This constructor for std::vector
, btw, also take a couple more arguments with the second being the value to fill your vector with so you could do foo() : bar(42, -1) {}
to fill your vector with values of -1
.
Upvotes: 3
Reputation: 122011
Add a constructor and use the initializer list:
struct foo {
foo() : bar(42) {}
std::vector<int> bar;
};
If your compiler supports C++11 features use std::array<>
instead.
struct foo {
std::array<int, 42> bar;
};
Or boost::array<>
if C++11 is not available and boost is permitted.
Upvotes: 3
Reputation: 258678
Use a constructor:
struct foo{
std::vector<int> bar;
foo() : bar(32) {}
};
Memory for the vector will automatically be allocated when creating an instance. The initialization list initializes members before the constructor body executes.
Upvotes: 6
Reputation: 71009
You should set the size of the vector(i.e. call std::vector
's constructor) in the constructor of the structure(preferably in its initialization list).
Like so:
struct foo{
foo() : bar(42) {}
std::vector<int> bar;
};
Upvotes: 0