Thread: Initialize std::vector in .h?

  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
    28,413
    Use the constructor's initialiser list.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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, 03: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