开发者

Insert into 2D vector

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜