【问题标题】:Insert an element to a vector at run time C++.Throwing Runtime Error在运行时将元素插入向量 C++。引发运行时错误
【发布时间】:2012-09-06 06:24:20
【问题描述】:

我想在运行时将一些元素插入到向量中。 我来了。

本意是打印"Hello Hi I am Rasmi"

int main()
{
vector<string>vect;
vect.push_back("Hello");
vect.push_back("Hi");
vect.push_back("Rasmi");
for(vect<string>::iterator it = vect.begin(); it != vect.end(); ++it)
{
 if(*it == "Rasmi") // If it encounters "Rasmi"
    { it--;
         vect.insert(vect.begin()+2, "I am");
    }
   cout << *it;
}
}

但它会引发运行时错误。

【问题讨论】:

  • 如果您只在数组中查找字符串的一个实例,那么使用it=std::find(vect.begin(), vect.end(), "Rasmi") 通常更容易

标签: c++ string vector iterator


【解决方案1】:
vect.insert(vect.begin()+2, "I am");
 }
cout << *it;

在你改变拥有的容器后,迭代器将失效 - 即你不能在 insertpush_back 之后使用 it...

添加元素后,向量可能需要自动调整大小和重新分配,如果发生这种情况,迭代器将不再有效。

【讨论】:

  • 我赞成您的回答,但最后一句话听起来像是开发人员有责任正确调整矢量大小。
  • 只有在如果向量被调整大小或分配时,位于插入点之前的迭代器才会失效。也许这就是您的意思,但听起来您是在说每次调用 insertpush_back 都会使每个迭代器无效。
  • @ZdeslavVojkovic 这是真的,我的措辞很糟糕。
  • @BenjaminLindley 好吧,从技术上讲,您应该将每个可变操作视为无效。
  • @BenjaminLindley 我宁愿确定也不要每次都检查新旧尺寸。
【解决方案2】:

虽然我真的不知道您为什么需要这样做,但有一个安全的解决方法。您可以存储迭代器的当前索引,将新元素插入向量中,然后重新分配迭代器以引用潜在的新内存地址。我已经在此处包含了执行此操作的代码。

if(*it == "Rasmi") // If it encounters "Rasmi"
{
    it--;
    int index = it - vect.begin (); // store index of where we are
    vect.insert(vect.begin()+2, "I am");
    it = vect.begin () + index; // vect.begin () now refers to "new" begin
    // we set it to be equal to where we would want it to be
}
cout << *it;

【讨论】:

    【解决方案3】:

    只要 std::vector::insert() 的重载之一具有签名 iterator insert ( iterator position, const T& x ) ,您就可以如下重写代码

    for(vect<string>::iterator it = vect.begin(); it != vect.end();)
    {
    
        if(*it == "Rasmi") // If it encounters "Rasmi"
        { 
            it = vect.insert(it, "I am");          
            cout << *it; 
            ++it;
        }
        cout << *it;
    
        ++it;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多