Initializing length of std::vector
Hello,
I know that when writing a class declaration, if the class contains an array of fixed length, then the length of that array can be initialized in the class declaration, without having to do so in the constructor. For example :
Code:
class MyClass
{
int my_array[100];
};
But, is it also possible to do this with an std::vector? For example :
Code:
class MyClass
{
std::vector<int> my_vector(100);
};
Or can the length of std::vectors only be set in the class constructor?
Thanks :)
Re: Initializing length of std::vector
Quote:
Originally Posted by
karnavor
But, is it also possible to do this with an std::vector? For example :
std::vector is no different than any C++ class. If it needs to be initialized on construction of the containing object, then you initialize it in the object's initialization list.
Code:
#include <vector>
class MyClass
{
std::vector<int> my_vector;
public:
MyClass() : my_vector(100) { }
};
Regards,
Paul McKenzie
Re: Initializing length of std::vector
And you can always use method resize() to change the number of the elements in the vector.
For a tutorial I recommend this: http://www.codeguru.com/cpp/cpp/cpp_...icle.php/c4027.