简体   繁体   中英

Insert an element to a vector at run time C++.Throwing Runtime Error

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

The intention is to print "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;
}
}

But it throwing run time error.

vect.insert(vect.begin()+2, "I am");
 }
cout << *it;

iterators are invalidated after you mutate the owning container - ie you can't use it after you insert or push_back ...

After you add elements, the vector might need to be resized and reallocated automatically, and if that happens, the iterators are no longer valid.

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;

As soon as one of overloads of std::vector::insert() has signature iterator insert ( iterator position, const T& x ) you can rewrite your code as following

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM