DEV Community

dinhluanbmt
dinhluanbmt

Posted on

1

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)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay