C++ 算法 元素計數

一 寫在前面

  • C++ 標準庫算法主要定義於頭文件 < algorithm >, 一些用於數值處理的算法定義於頭文件< numeric > 。
  • 本文介紹 非更易型算法 中的用於 元素計數 的兩種算法:std::cout 和std::count_if。

二 std::count 和 std::count_if

  • 返回範圍 [first, last) 中滿足特定判別標準的元素數。
template< class InputIt, class T >
typename iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T &value );(1)(C++20)
template< class InputIt, class T >
constexpr typename iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T &value );(1)(C++20)
template< class ExecutionPolicy, class ForwardIt, class T >
typename iterator_traits<ForwardIt>::difference_type
count( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, const T &value );(2)(C++17)
template< class InputIt, class UnaryPredicate >
typename iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPredicate p );(3)(C++20)
template< class InputIt, class UnaryPredicate >
constexpr typename iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPredicate p );(3)(C++20)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
typename iterator_traits<ForwardIt>::difference_type
count_if( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, UnaryPredicate p );(4)(C++17)

三 Demo

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <string>

template <typename C>
void fill(C& container, int begin, int end) {
  for (auto i = begin; i <= end; i++) {
    container.emplace_back(i);
  }
}

template <typename C>
void print(const std::string& pre, C container) {
  std::cout << pre;
  std::copy(container.begin(), container.end(),
            std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
}

bool even(int a) {
  return a % 2  == 0;
}

int main() {

  std::vector<int> vc;
  fill(vc, 1, 9);
  vc.emplace_back(9);
  vc.emplace_back(9);
  {
    // count
    int count5 = std::count(vc.begin(), vc.end(), 5);
    int count9 = std::count(vc.begin(), vc.end(), 9);
    
    print("vc: ", vc);
    std::cout << "count of 5 in vc: " << count5 << std::endl;
    std::cout << "count of 9 in vc: " << count9 << std::endl;
  }
  {
    // count_if
    int count  = std::count_if(vc.begin(), vc.end(), even);
    std::cout << "count of even numbers in vc: " << count << std::endl;
  }

  std::cin.get();
  return 0;
}
template <typename C>
void print1(const std::string& pre, C container) {
  std::cout << pre;
  for(auto it = container.begin(); it != container.end(); it++) {
    std::cout << *it << " ";
  }
  std::cout << std::endl;
}
  • 結果:
vc: 1 2 3 4 5 6 7 8 9 9 9
count of 5 in vc: 1
count of 9 in vc: 3
count of even numbers in vc: 4

四 參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章