Функция подсчета в C++: различные методы подсчета вхождений

В C++ функция count обычно используется для подсчета вхождений определенного значения в диапазон или контейнер. В C++ существует несколько способов использования функции count. Вот несколько примеров:

  1. Использование алгоритмов стандартной библиотеки:

    #include <algorithm>
    #include <vector>
    int main() {
       std::vector<int> numbers = {1, 2, 2, 3, 2, 4, 2, 5};
       int count = std::count(numbers.begin(), numbers.end(), 2);
       // count is now 4, as 2 appears 4 times in the vector
       return 0;
    }
  2. Использование цикла for на основе диапазона:

    #include <iostream>
    #include <vector>
    int main() {
       std::vector<int> numbers = {1, 2, 2, 3, 2, 4, 2, 5};
       int target = 2;
       int count = 0;
       for (int num : numbers) {
           if (num == target)
               count++;
       }
    // count is now 4, as 2 appears 4 times in the vector
       return 0;
    }
  3. Использование итераторов:

    #include <iostream>
    #include <vector>
    int main() {
       std::vector<int> numbers = {1, 2, 2, 3, 2, 4, 2, 5};
       int target = 2;
       int count = 0;
       for (auto it = numbers.begin(); it != numbers.end(); ++it) {
           if (*it == target)
               count++;
       }
    // count is now 4, as 2 appears 4 times in the vector
       return 0;
    }