C++ Set 庫 - count 函式



描述

它搜尋容器中與 val 等價的元素,並返回匹配的數量。

宣告

以下是 std::set::count 在不同 C++ 版本中的工作方式。

C++98

size_type count (const value_type& val) const;

C++11

size_type count (const value_type& val) const;

返回值

它返回匹配的數量。

異常

如果丟擲異常,容器中不會有任何更改。

時間複雜度

時間複雜度取決於對數。

示例

以下示例顯示了 std::set::count 的用法。

#include <iostream>
#include <set>

int main () {
   std::set<int> myset;

   for (int i = 1; i < 15;++i) myset.insert(i*5);

   for (int i = 0; i < 5; ++i) {
      std::cout << i;
      if (myset.count(i)!=0)
         std::cout << " is an element of myset.\n";
      else
         std::cout << " is not an element of myset.\n";
   }

   return 0;
}

以上程式將編譯並正確執行。

0 is not an element of myset.
1 is not an element of myset.
2 is not an element of myset.
3 is not an element of myset.
4 is not an element of myset.
set.htm
廣告