【问题标题】:Inserting a vector into a vector of vectors将向量插入向量的向量中
【发布时间】:2018-06-05 06:37:09
【问题描述】:

我正在制作一种使用向量向量的插入排序程序。我想知道如何将向量插入向量的向量中。

// constructing vector of vectors
vector< vector< int > > v_of_v;
for (int i = 0; i < 3; i++) {
    vector<int> row(2, i*100);
    v_of_v.push_back(row);
}

vector<int> tmp(2, 1);

// predetermined index
index = 2;

v_of_v.insert(index, tmp); // doesnt work

我看到的示例只是遍历了 tmp 并插入了向量的每个元素,这不是我想要的。我希望能够插入向量本身,就像 push_back 一样。

【问题讨论】:

  • insertiterator 作为第一个参数,而不是索引。你(可能?)想写v_of_v.insert(v_of_v.begin() + index, tmp);
  • 请注意,在向量中间插入元素是低效的。因为它需要所有以下元素移动(复制许多元素)。对于此任务,使用 std::list 效率更高

标签: c++ vector


【解决方案1】:

试试这个:

v_of_v.insert(v_of_v.begin() + index, tmp); 

【讨论】:

  • 谢谢,解决了。我一定认为可以使用索引来代替迭代器。
猜你喜欢
  • 1970-01-01
  • 2014-02-24
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多