C ++ set count()函数用于返回在容器中找到的元素数。由于set容器不包含任何重复元素,因此如果set容器中存在val值的元素,则此函数实际上返回1,否则返回0。
size_type count (const value_type& val) const;
val:要在集合容器中搜索的值。
如果set容器中存在值val的元素,则返回1,否则返回0。
大小为对数。
没有变化。
容器被访问。
同时访问集合的元素是安全的。
如果引发异常,则容器中没有任何更改。
让我们看一个简单的示例,使用给定的键值搜索元素:
#include <iostream>
#include <set>
using namespace std;
int main()
{
//初始化容器
set<int> mp;
// 按随机顺序插入元素
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()函数检查给定值。如果元素存在于集合容器中,则它将显示消息,指出存在元素,否则不存在。
让我们看一个简单的实例来搜索集合的元素:
#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()函数用于搜索集合中的“ 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' 出现在集合中 \n";
}
if (m.count('z') == 0) {
cout << " 'z' 没有出现在集合中" << endl;
}
return 0;
}输出:
'a' 出现在集合中 'z' 没有出现在集合中
在上面的示例中,键“ a”出现在集合m中,因此它是“ a”的值,而键“ z”不出现在集合中,因此没有值“ z”。
让我们看一个简单的实例:
#include <set>
#include <iostream>
int main()
{
using namespace std;
set<int> s1;
set<int>::size_type i;
s1.insert(1);
s1.insert(1);
// 键在集合中必须是唯一的,所以重复的键将被忽略
i = s1.count(1);
cout << "s1中排序键为1的元素数为: "
<< i << "." << endl;
i = s1.count(2);
cout << "s1中排序键为2的元素数为: "
<< i << "." << endl;
}输出:
s1中排序键为1的元素数为: 1. s1中排序键为2的元素数为: 0.