CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2009
    Posts
    68

    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

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Initializing length of std::vector

    Quote Originally Posted by karnavor View Post
    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

  3. #3
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    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.
    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured