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

    std::vector as a static member

    Hello,

    I have a class with a vector as a static member:
    Code:
    class MyClass
    {
         static std::vector<int> my_vector;
    }
    I then wish to initialize the vector in the .cpp file in global scope:
    Code:
    std::vector<int> my_vector = std::vector<int>(10);
    my_vector[0] = 5;
    But this gives me some errors. How can I initialize the values of my_vector? Thanks.

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

    Re: std::vector as a static member

    Quote Originally Posted by ejohns85 View Post
    Hello,

    I have a class with a vector as a static member:
    Code:
    class MyClass
    {
         static std::vector<int> my_vector;
    }
    I then wish to initialize the vector in the .cpp file in global scope:
    Code:
    std::vector<int> my_vector = std::vector<int>(10);
    my_vector[0] = 5;
    But this gives me some errors. How can I initialize the values of my_vector? Thanks.
    What are the errors? Also, please post compilable code so we can see what you're doing.
    Code:
    #include <vector>
    class MyClass
    {
         static std::vector<int> my_vector;
    };
    //....
    // In one CPP file outside of any function:
    std::vector<int> MyClass::my_vector(10);
    The code below is not initialization -- it is assignment
    Code:
    my_vector[0] = 5;
    Therefore it must be done within a function.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Jan 2011
    Posts
    101

    Re: std::vector as a static member

    Code:
    class Foo
    {
    public:
       static std::vector<int> v;
    };
    // Foo.cpp
    std::vector<int> Foo::v = std::vector<int>(5);
    ...
    int main()
    {
    ...
       Foo::v.push_back(3);
       Foo::v.push_back(1);
       Foo::v.push_back(8);
       Foo::v.push_back(6);
       Foo::v.push_back(2);
    ...
       std::cout << "v[0] = " << v[0] << std::endl;
    }

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: std::vector as a static member

    You can use Boost.Assign:

    Code:
    std::vector<int> Foo::v = boost::assign::list_of(5)(10)(15)(20); // as long as you like
    If you don't want that dependency, this will produce the same result:
    Code:
    vector<int> initializeVector()
    {
        vector<int> v;
        v.push_back(5);
        v.push_back(10);
        v.push_back(15);
        v.push_back(20);
        return v;
    }
    
    std::vector<int> Foo::v = initializeVector();

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