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

1 Answer

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

int main() {
    std::vector<int> vec{ 1, 1, 2, 3, 3, 3, 3, 5, 7, 7, 7, 8, 9 };
    int number = 3;
    
    int count = std::upper_bound(vec.begin(), vec.end(), number) - std::lower_bound(vec.begin(), vec.end(), number); 
    
    std::cout << count;
}



/*
run:

4

*/

 



answered Jul 14, 2023 by avibootz
...