C++ 演算法庫 - count() 函式



描述

C++ 函式std::algorithm::count() 返回值在範圍內的出現次數。此函式使用運算子 ==進行比較。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::count() 函式的宣告。

C++98

template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& val);

引數

  • first - 輸入迭代器,指向搜尋序列的初始位置。

  • last - 輸入迭代器,指向搜尋序列的最終位置。

  • val - 要在範圍內搜尋的值。

返回值

返回範圍內的元素數量firstlast.

異常

如果元素賦值或迭代器上的操作引發異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

在兩者之間的距離上是線性的firstlast.

示例

以下示例顯示了 std::algorithm::count() 函式的使用方法。

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

using namespace std;

int main(void) {
   vector<int> v = {1, 3, 3, 3, 3};
   int cnt;

   cnt = count(v.begin(), v.end(), 3);

   cout << "Number 3 occurs " << cnt << " times." << endl;

   return 0;
}

讓我們編譯並執行以上程式,這將產生以下結果:

Number 3 occurs 4 times.
algorithm.htm
廣告