C ++ set count()函數(shù)用于返回在容器中找到的元素數(shù)。由于set容器不包含任何重復(fù)元素,因此如果set容器中存在val值的元素,則此函數(shù)實(shí)際上返回1,否則返回0。
size_type count (const value_type& val) const;
val:要在集合容器中搜索的值。
如果set容器中存在值val的元素,則返回1,否則返回0。
大小為對數(shù)。
沒有變化。
容器被訪問。
同時訪問集合的元素是安全的。
如果引發(fā)異常,則容器中沒有任何更改。
讓我們看一個簡單的示例,使用給定的鍵值搜索元素:
#include <iostream>
#include <set>
using namespace std;
int main()
{
//初始化容器
set<int> mp;
// 按隨機(jī)順序插入元素
mp.insert(30);
mp.insert( 40 );
mp.insert( 60 );
mp.insert( 20);
mp.insert( 50 );
// 檢查鍵30是否存在
if (mp.count(30))
cout << "鍵30存在\n";
else
cout << "鍵30不存在\n";
// 檢查鍵100是否存在
if (mp.count(100))
cout << "鍵100存在\n";
else
cout << "鍵100不存在\n";
return 0;
}輸出:
鍵30存在 鍵100不存在
在上面的示例中,count()函數(shù)檢查給定值。如果元素存在于集合容器中,則它將顯示消息,指出存在元素,否則不存在。
讓我們看一個簡單的實(shí)例來搜索集合的元素:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<char> myset;
char c;
myset = {'a', 'c', 'f'};
for (c='a'; c<'h'; c++)
{
cout << c;
if (myset.count(c)>0)
cout << " 是myset的元素。\n";
else
cout << " 不是myset的元素。\n";
}
return 0;
}輸出:
a 是myset的元素。 b 不是myset的元素。 c 是myset的元素。 d 不是myset的元素。 e 不是myset的元素。 f 是myset的元素。 g 不是myset的元素。
在上面的示例中,count()函數(shù)用于搜索集合中的“ a”-“ h”元素。
讓我們看一個簡單的示例來搜索集合中的鍵:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> m = {'a','b','c','d'};
if (m.count('a') == 1) {
cout<< " 'a' 出現(xiàn)在集合中 \n";
}
if (m.count('z') == 0) {
cout << " 'z' 沒有出現(xiàn)在集合中" << endl;
}
return 0;
}輸出:
'a' 出現(xiàn)在集合中 'z' 沒有出現(xiàn)在集合中
在上面的示例中,鍵“ a”出現(xiàn)在集合m中,因此它是“ a”的值,而鍵“ z”不出現(xiàn)在集合中,因此沒有值“ z”。
讓我們看一個簡單的實(shí)例:
#include <set>
#include <iostream>
int main()
{
using namespace std;
set<int> s1;
set<int>::size_type i;
s1.insert(1);
s1.insert(1);
// 鍵在集合中必須是唯一的,所以重復(fù)的鍵將被忽略
i = s1.count(1);
cout << "s1中排序鍵為1的元素數(shù)為: "
<< i << "." << endl;
i = s1.count(2);
cout << "s1中排序鍵為2的元素數(shù)為: "
<< i << "." << endl;
}輸出:
s1中排序鍵為1的元素數(shù)為: 1. s1中排序鍵為2的元素數(shù)為: 0.