【问题标题】:C++ Can't insert into empty vectorC ++无法插入空向量
【发布时间】:2020-04-27 11:14:31
【问题描述】:

当我尝试将向量插入空向量时,出现长度错误:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
  vector<int> v1;
  vector<int> v2 = {1};
  v1.insert(v2.begin(), v2.end(), v1.end());

}

terminate called after throwing an instance of 'std::length_error'
  what():  vector::_M_range_insert

这是预期的行为吗?我认为插入会在必要时自动增加向量的大小。它应该在 v1.end() 后面插入,即使它是空的,也会填满向量。

【问题讨论】:

  • 你想要:v1.insert(v1.end(), v2.begin(), v2.end()); ?

标签: c++ vector insert


【解决方案1】:

正确的语法是:

v1.insert(v1.begin(), v2.begin(), v2.end());

或:

v1.insert(v1.end(), v2.begin(), v2.end());

【讨论】:

  • 第一个参数应该是目的地的位置
猜你喜欢
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2020-06-28
相关资源
最近更新 更多