Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert object at index of vector c++

Tags:

c++

vector

I need to insert an object to existing vector of objects. I know that i need to use iterator to do it but i dont know how it exactly works.

I have alphabetically sorted vector and i need to insert new object by its name in exact index that i got after some search . So i have this.

vector<Person>people;


int index =54;
Person temp;

people.push_back(temp);//insert at end of vector
people.insert(index, temp);//doesnt work for int

Can anyone help me how to use iterator properly to insert my object to 54th index of vector and move all following object by one index ?

Thank you for any help.

like image 571
Pastx Avatar asked Nov 20 '25 13:11

Pastx


2 Answers

The straight forward answer is you need an iterator. The iterator for std::vector supports random access, which means you can add or subtract an integer value to or from an iterator.

people.insert(people.begin() + index, temp);

The better answer is don't use an index, use an iterator. What is your loop? You should be able to refactor the loop to use an iterator instead of an index.

like image 61
Jeffery Thomas Avatar answered Nov 23 '25 02:11

Jeffery Thomas


I have alphabetically sorted vector and i need to insert new object by its name in exact index that i got after some search.

If the vector is sorted alphabetically, then the proper way of inserting an item in the correct position while maintaining the sort order is using the upper_bound function:

people.insert(upper_bound(people.begin(), people.end(), temp), temp);

The function searches the sorted range, and returns the position of the first element that is greater than temp.

Here is a demo on ideone.

like image 39
Sergey Kalinichenko Avatar answered Nov 23 '25 03:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!