开发者

Insert into 2D vector

开发者 https://www.devze.com 2023-01-18 08:16 出处:网络
Could you do the insert operation in one line along with allocating memory for internal vector? vector <vector<int>> myvector;

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<开发者_StackOverflow中文版int>()); //allocate memory for internal vector
      myvector[index].insert(myvector[index].begin(), a, &a[5]); //insert
  }


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.


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] ) );
0

精彩评论

暂无评论...
验证码 换一张
取 消