Daily C++ - Number of Elements in an Interval

cpp::daily Episode 006.


Daily C++ - Number of Elements in an Interval

std::count_if returns the number of elements in the range [first, last) meeting specific criteria, that is, number of elements that satisfy the condition. Exceptions

Syntax

count_if

Example

Know how many elements in vector vec have zero remainder when divided by 2!

#include <iostream>
#include <vector>
#include <algorithm>

bool resto_zero( int &i ){
  return ( i % 2 == 0 );
}

int main( int argc, char ** argv ){

  std::vector<int> vec {  11, 20, 9, 36, 88, 54, 55 };
  int pares = std::count_if( vec.begin(), vec.end(), resto_zero );
  std::cout << pares << '\n'; // 4

  return 0;
}

Other example

How many words from our group are there in the sentence: “That day everything was very quiet.

#include <iostream>
#include <vector>
#include <algorithm>

bool grep( const std::string &word ){
  const std::string phrase {"That day everything was very quiet."};
  int pos = phrase.find( word );
  return ( pos >= 0 );
}

int main( int argc, char ** argv ){

  std::vector<std::string> word {"very", "nothing", "cool", "day", "everything", "thanks"};
  int send = std::count_if( word.begin(), word.end(), grep );
  std::cout << send << '\n'; // 3 → very, everything and day

  return 0;
}

Simple, right?!


cpp cppdaily


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles