We help IT Professionals succeed at work.

# inserting elements in existing vector

on
Medium Priority
209 Views
hi everyone,

I have a question about inserting values in a vector that already has some elements.

Suppose a vector of integers "a" has 5 existing elements i.e. a,a.....a. Now I want to add, say 3 values between a and a. That means the vector should become a,a,a,a,a.....a. Here a,a and a are 3 new values I wanted to add and old a (before modification ) should become a.

Thanks for your time and help.

abybaby.
Comment
Watch Question

## View Solution Only

Commented:
hi everyone,

well, I solved problem myself but still I would appreciate if you have any other method of dealing the problem which is more efficient.
Also, I have a question. Is it better to do all the insertion operation using a list and then copy the values in a vector for later use in the program.

here is the solution code.

typedef vector<int> INT;
int main()
{

INT a;
a.push_back(0);
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
int index=1;
INT::iterator i,where;
where=a.begin()+index;
a.insert(where,10);
where++;
a.insert(where,11);

for (i=a.begin();i!=a.end();i++)
{
cout<<(*i)<<endl;
}
return 1;
}

Commented:
Inserting in the middle of a vector is always expensive
Why don't u use list instead of a vector

Amit
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
Unlock the solution to this question.