Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Count function in C++

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 186
    Comment on it

    If you want to count the presence of a element in a given range, then you can use the count() function defined in the STL algorithm. It returns the number of variable inside a range whose value is equal to the given number.

    Template for count

    template <class InputIterator, class T>
      typename iterator_traits<InputIterator>::difference_type
        count (InputIterator first, InputIterator last, const T& val);
    

    About parameters
    InputIterator first
    InputIterator for the initial position of the range which is included in the range.
    InputIterator last
    InputIterator for the final position which it not included in the range.
    val
    value to count in the given range.

    Sample program using count

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
            vector <int> v;
            vector <int>:: iterator it;
            int result;
    
            // Pushing 11 random integer elements inside the vector
            v.push_back(1);
            v.push_back(2);
            v.push_back(3);
            v.push_back(4);
            v.push_back(2);
            v.push_back(5);
            v.push_back(2);
            v.push_back(6);
            v.push_back(21);
            v.push_back(6);
            v.push_back(2);
    
            // printing the elements inside the range
            cout <<"Elements inside the range " << endl;
            for ( it = v.begin(); it != v.end(); it++)
                    cout << *it << " ";
            cout << endl;
    
            //counting the occourance of 2 in range
            result = count(v.begin(),v.end(),2);
            cout <<"2 found " << result << " times in the range." << endl;
    
            //counting the occourance of 23 in range
            result = count(v.begin(),v.end(),23);
            cout <<"23 found " << result << " times in the range." << endl;
    
            return 0;
    }
    

    Output of the above program

    Elements inside the range 
    1 2 3 4 2 5 2 6 21 6 2 
    2 found 4 times in the range.
    23 found 0 times in the range.
    

    Time complexity for count is linear in between the range.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: