![]() |
VOOZH | about |
In C++, inserting element in a sorted vector should be done such that it preserves the order of elements. In this article, we will learn different methods to insert an element in a sorted vector in C++.
The recommended way to insert an element is to first find the position of insertion using lower_bound() function and then insert the element using vector insert(). Let's take a look at an example:
1 2 3 4 5
Explanation: The lower_bound() function returns the position where the given element should be present in the sorted vector. The new element is then inserted at this position using the vector insert() function.
We can also use the vector emplace() method in place of vector insert().
C++ also provides a few more methods to insert an element in a sorted vector. Some of them are given below:
Table of Content
Just like lower_bound(), the upper_bound() function can also be used to find the correct position to insert an element in the sorted vector using vector emplace().
1 2 3 4 5
The merge() function can be used to insert the given element in sorted vector by adding the element to a temporary vector and then merging them.
1 2 3 4 5
The simplest method is to add the element at the end of the vector using vector push_back() and then sort the vector using sort() function.
1 2 3 4 5
This method is generally not very efficient when the number of elements to be inserted is much less than the total number of elements.
As the vector is sorted, custom binary search operation can be applied to find the position of where to insert the element. Then the element can be inserted at this position using vector insert().
1 2 3 4 5