DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, insert value to sorted vector

To insert a new value into a sorted integer vector while maintaining the sorted order, you can use the std::lower_bound algorithm from the library.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
    vector<int> sortedVec = {1, 3, 5, 7, 9};  //sorted vector
    int val = 4;  // Value to insert
    // Find the position to insert the new value using lower_bound
    auto it = std::lower_bound(sortedVec.begin(), sortedVec.end(), val);

    // Insert the new value at the determined position
    sortedVec.insert(insertPos, val);

    // Print the updated vector
    for (int num : sortedVec) {
        cout << num << " ";
    }
    cout <<endl;
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)