|
-
July 12th, 2010, 07:18 AM
#1
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
-
July 12th, 2010, 07:36 AM
#2
Re: Initializing length of std::vector
 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
-
July 12th, 2010, 02:05 PM
#3
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|