Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,848 questions

51,769 answers

573 users

How to find the index of N in a sorted vector if N is not present, return the index where it would be in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <algorithm> // for std::lower_bound

// Function to find the index where N would be inserted
int findInsertPosition(const std::vector<int>& arr, int N) {
    auto it = std::lower_bound(arr.begin(), arr.end(), N);
    
    return it - arr.begin(); // Return the index
}

int main() {
    std::vector<int> arr = {1, 3, 5, 7, 8, 9, 12, 15}; // Sorted array
    int N = 6; // Element to find or insert

    int index = findInsertPosition(arr, N);

    std::cout << "Index where " << N << " is OR would be: " << index << std::endl;
}



/*
run:

Index where 6 is OR would be: 3

*/

 



answered Sep 20, 2025 by avibootz
0 votes
#include <iostream>
#include <vector>

// Function to find the index and check existence
void findOrInsertPosition(const std::vector<int>& arr, int N) {
    auto it = std::lower_bound(arr.begin(), arr.end(), N);
    int index = it - arr.begin();

    if (it != arr.end() && *it == N)
        std::cout << "Found at index: " << index << std::endl;
    else
        std::cout << "Index where " << N << " would be: " << index << std::endl;
}

int main() {
    std::vector<int> arr = {1, 3, 5, 7, 8, 9, 12, 15}; // Sorted array
    int N = 6; // Element to find or insert

    findOrInsertPosition(arr, N);    
    findOrInsertPosition(arr, 9);
}



/*
run:

Index where 6 would be: 3
Found at index: 5

*/

 



answered Sep 20, 2025 by avibootz
...