count

STL algorithm count can help us to count the elements that are equal to value.
Its syntax is like the following form:
C++
template< class InputIt, class T >
typename iterator_traits<InputIt>::difference_type
    count( InputIt first, InputIt last, const T &value );
Example:
C++
#include 
#include 
#include 
using namespace std;

int main(int argc, char *argv[])
{
    vector<int> vec{ 1, 2, 3, 4, 4, 3, 4, 8, 3 };
    cout << "the count of 4: " << count( vec.begin(), vec.end(), 4 ) << endl;
    return 0;
}
/*
the count of 4: 3
*/

count_if

STL algorithm count_if can help us to calculate the number of elements which satisfy the special expression.
Its syntax is like the following form:
C++
template< class InputIt, class UnaryPredicate >
typename iterator_traits<InputIt>::difference_type
    count_if( InputIt first, InputIt last, UnaryPredicate p );
Example:
C++
#include 
#include 
#include 
using namespace std;

int main(int argc, char *argv[])
{
    vector<int> vec;
    for( int i = 1; i < 11; ++i )
    {
        vec.push_back( i );
    }
    cout << "the count of multiple of 3: " << count_if( vec.begin(), vec.end(),
                                                        []( int element ){ return 0 == element%3; } )
         << endl;
    return 0;
}
/*
the count of multiple of 3: 3
*/

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x