C++ Tutorial/vector/vector count


Deprecated: Constant E_STRICT is deprecated in /var/www/cppe.ru/www/includes/exception/MWExceptionHandler.php on line 179

Deprecated: Creation of dynamic property PPDStack::$accum is deprecated in /var/www/cppe.ru/www/includes/parser/Preprocessor_DOM.php on line 803

Deprecated: Constant E_STRICT is deprecated in /var/www/cppe.ru/www/includes/exception/MWExceptionHandler.php on line 179

Deprecated: Constant E_STRICT is deprecated in /var/www/cppe.ru/www/vendor/mediawiki/at-ease/src/Functions.php on line 48
Материал из C\C++ эксперт
Перейти к: навигация, поиск

Count elements in a vector by value

#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
int main()
{
   std::ostream_iterator< int > output( cout, " " );
   int a2[ 10 ] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 };
   std::vector< int > v2( a2, a2 + 10 ); // copy of a2
   cout << "Vector v2 contains: ";
   std::copy( v2.begin(), v2.end(), output );
   // count number of elements in v2 with value 8
   int result = std::count( v2.begin(), v2.end(), 8 );
   cout << "\nNumber of elements matching 8: " << result;
   cout << endl;
   return 0;
}
Vector v2 contains: 100 2 8 1 50 3 8 8 9 10
Number of elements matching 8: 3