initalizing vectors

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joe Laughlin

    #1

    initalizing vectors

    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


  • Victor Bazarov

    #2
    Re: initalizing vectors

    "Joe Laughlin" <Joseph.V.Laugh lin@boeing.com> wrote...[color=blue]
    > Is there any way to initialize a vector with a bunch of values at once,
    > instead of doing a bunch of push_back()'s?[/color]

    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


    Comment

    • Gianni Mariani

      #3
      Re: initalizing vectors

      Joe Laughlin wrote:[color=blue]
      > Is there any way to initialize a vector with a bunch of values at once,
      > instead of doing a bunch of push_back()'s?[/color]

      template<typena me 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<flo at> v = Initialize( a );
      }

      - or look at :

      This page provides a list of the pages of BDSoft.com, and a little info about each one. If you are lost on our site, try using the sitemap to find what you are looking for.


      G

      Comment

      • Siemel Naran

        #4
        Re: initalizing vectors

        "Joe Laughlin" <Joseph.V.Laugh lin@boeing.com> wrote in message
        [color=blue]
        > Is there any way to initialize a vector with a bunch of values at once,
        > instead of doing a bunch of push_back()'s?[/color]

        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.


        Comment

        Working...