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.
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.