Initialize std::vector in .h?

This is a discussion on Initialize std::vector in .h? within the C++ Programming forums, part of the General Programming Boards category; My class has a std::vector member that works fine when declared like this - Code: private: std::vector<Position> path; But I ...

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    117

    Initialize std::vector in .h?

    My class has a std::vector member that works fine when declared like this -
    Code:
    private:
        std::vector<Position> path;
    But I want to be able to give it an initial size (of say 20) like
    Code:
    private:
        std::vector<Position> path(20, 0);
    But g++ complains when I do this, which I kinda expected it would. Is there a way to get around this? I tried to make a local vector in my constructor with that size and then set it equal to it like -
    Code:
    Path::Path() {std::vector<Position> temp(20); path = temp;}
    But when I tried to access path.at(19) to test it, I got a segmentation fault. Can someone explain why this way won't work and/or a way to accomplish this? Any help is appreciated.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,119
    Use the constructor's initialiser list.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    117
    Oh, of course. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Initialize elements to zero
    By Eman in forum C++ Programming
    Replies: 5
    Last Post: 03-16-2011, 04:59 PM
  2. initialize a string to nothing?
    By towed in forum C Programming
    Replies: 3
    Last Post: 12-16-2010, 03:15 AM
  3. Simple Question memset(vector<int>, 0, sizeof(vector<int>))
    By HyperShadow in forum C++ Programming
    Replies: 6
    Last Post: 12-10-2007, 04:56 PM
  4. Failing to initialize COM
    By andyhunter in forum Windows Programming
    Replies: 8
    Last Post: 12-22-2004, 03:43 PM
  5. Initialize COM
    By The15th in forum Windows Programming
    Replies: 7
    Last Post: 01-20-2002, 09:55 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21