在运行时C ++将元素插入向量。抛出运行时错误 [英] Insert an element to a vector at run time C++.Throwing Runtime Error

查看:142
本文介绍了在运行时C ++将元素插入向量。抛出运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to insert some element(s) into a vector at the run time. Here I go.

目的是打印你好我是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;
}
}

但它会导致运行时错误。

But it throwing run time error.

推荐答案

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

Although I really don't know why you'd need to do such a thing, there is a safe workaround. You can store the current index of the iterator, insert the new element into the vector, then reassign the iterator to reference the potential new memory address. I've included the code to do so here.

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;

这篇关于在运行时C ++将元素插入向量。抛出运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆