How to count the occurrences of a number in sorted array with C++

1 Answer

0 votes
#include <iostream>
#include <algorithm>

int main() {
    int arr[] = { 1, 1, 2, 3, 3, 3, 3, 5, 7, 7, 7, 8, 9 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int number = 3;
    
    int count = std::upper_bound(arr, arr + size, number) - std::lower_bound(arr, arr + size, number); 
    
    std::cout << count;
}



/*
run:

4

*/

 



answered Jul 14, 2023 by avibootz
...