tags:

views:

50

answers:

2

Could you do the insert operation in one line along with allocating memory for internal vector?

  vector <vector<int>> myvector;

  int a[] = {0, 1, 2, 3, 4};

  for (int index = 0; index < 2; index++)
  {
      myvector.push_back(vector<int>()); //allocate memory for internal vector
      myvector[index].insert(myvector[index].begin(), a, &a[5]); //insert
  }
+2  A: 

Yes, std::vector has a template constructor which takes a pair of iterators so you can use:

myvector.push_back( std::vector<int>( a, a + 5 ) );

A pair of pointers works as a pair of iterators.

Charles Bailey
ah the constructor..
xor
A: 

Minimizing data copy from array into vector might be important for performance if dimensions get bigger:

std::vector <std::vector<int>> myvector(2);
int a[] = {0, 1, 2, 3, 4};
size_t elements = sizeof(a) / sizeof(int);

myvector[0].reserve(elements);
std::copy ( a, a + elements, std::back_inserter ( myvector[0] ) );
Steve Townsend