initalizing vectors

Discussion in 'C++' started by Joe Laughlin, Oct 19, 2004.

  1. Joe Laughlin

    Joe Laughlin Guest

    Is there any way to initialize a vector with a bunch of values at once,
    instead of doing a bunch of push_back()'s?

    Thanks,
    Joe
    Joe Laughlin, Oct 19, 2004
    #1
    1. Advertising

  2. "Joe Laughlin" <> wrote...
    > Is there any way to initialize a vector with a bunch of values at once,
    > instead of doing a bunch of push_back()'s?


    Yes, if you don't mind having those values in an array:

    int array[] = { 1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6 };
    std::vector<int> vi(array, array + (sizeof array / sizeof array[0]));

    V
    Victor Bazarov, Oct 19, 2004
    #2
    1. Advertising

  3. Joe Laughlin wrote:
    > Is there any way to initialize a vector with a bunch of values at once,
    > instead of doing a bunch of push_back()'s?


    template<typename T, unsigned N>
    std::vector<T> Initialize( const T (&i_v)[N] )
    {
    return std::vector<T>( &(i_v[0]), &(i_v[N]) );
    }

    int foo()
    {
    float a[] = { 1.2, 2.3 };

    std::vector<float> v = Initialize( a );
    }

    - or look at :

    http://www.bdsoft.com/tools/initutil.html

    G
    Gianni Mariani, Oct 19, 2004
    #3
  4. Joe Laughlin

    Siemel Naran Guest

    "Joe Laughlin" <> wrote in message

    > Is there any way to initialize a vector with a bunch of values at once,
    > instead of doing a bunch of push_back()'s?


    If you want to initialize all elements to the same value:

    vector<int> v(10, -1);

    Other posts talk about initializing from an array, also very useful.
    Siemel Naran, Oct 19, 2004
    #4
    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. Anand P Paralkar
    Replies:
    2
    Views:
    9,338
    Srinivasan Venkataramanan
    Aug 4, 2003
  2. Lily
    Replies:
    16
    Views:
    1,287
    Bob Jenkins
    May 10, 2004
  3. Analog Guy

    Conditional Check on Vectors

    Analog Guy, Oct 6, 2004, in forum: VHDL
    Replies:
    3
    Views:
    524
    Paul Uiterlinden
    Oct 7, 2004
  4. Replies:
    3
    Views:
    664
    Shadowman
    Mar 26, 2008
  5. Guest
    Replies:
    0
    Views:
    414
    Guest
    Sep 14, 2005
Loading...

Share This Page