initialising a static std::vector data member

Discussion in 'C++' started by Dylan, Jan 12, 2005.

  1. Dylan

    Dylan Guest

    what is the best way of initializing a static std::vector data member
    with some values?

    (currently I just push_back some values in the constructor if the size
    == 0)

    thanks
     
    Dylan, Jan 12, 2005
    #1
    1. Advertising

  2. Dylan

    Rolf Magnus Guest

    Dylan wrote:

    > what is the best way of initializing a static std::vector data member
    > with some values?


    By static, you mean static member? You can initialize it with an array.

    #include <vector>
    #include <iostream>

    struct Foo
    {
    static std::vector<int> vec;
    private:
    static const int array[];
    };

    const int Foo::array[] = { 1, 10, 100, 1000, 10000, 42 };
    std::vector<int> Foo::vec(array, array + sizeof(array)/sizeof(*array));

    int main()
    {
    std::cout << Foo::vec.back() << '\n';
    }

    If your vector is also constant, you might just as well use the array
    directly instead.
     
    Rolf Magnus, Jan 12, 2005
    #2
    1. Advertising

  3. Dylan

    Dylan Guest

    thanks Rolf

    On Wed, 12 Jan 2005 15:07:59 +0100, Rolf Magnus <>
    wrote:

    >Dylan wrote:
    >
    >> what is the best way of initializing a static std::vector data member
    >> with some values?

    >
    >By static, you mean static member? You can initialize it with an array.
    >
    >#include <vector>
    >#include <iostream>
    >
    >struct Foo
    >{
    > static std::vector<int> vec;
    >private:
    > static const int array[];
    >};
    >
    >const int Foo::array[] = { 1, 10, 100, 1000, 10000, 42 };
    >std::vector<int> Foo::vec(array, array + sizeof(array)/sizeof(*array));
    >
    >int main()
    >{
    > std::cout << Foo::vec.back() << '\n';
    >}
    >
    >If your vector is also constant, you might just as well use the array
    >directly instead.
     
    Dylan, Jan 12, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Anonymous
    Replies:
    20
    Views:
    4,304
    Pete Becker
    Mar 30, 2005
  2. Jason Heyes
    Replies:
    8
    Views:
    727
    Andrew Koenig
    Jan 15, 2006
  3. Jens Henrik Goebbert

    initialising static member with static methode

    Jens Henrik Goebbert, Oct 24, 2007, in forum: C++
    Replies:
    3
    Views:
    964
  4. Rune Allnor
    Replies:
    4
    Views:
    953
    Rune Allnor
    Dec 11, 2008
  5. A L
    Replies:
    12
    Views:
    2,052
Loading...

Share This Page