C++ set count()函数
c++ set的count()函数用于返回在容器中找到的元素的数量。因为集合容器中没有重复的元素,所以如果值为val的元素在集合容器中存在,这个函数实际上返回1,否则返回0。
语法
size_type count (const value_type& val) const;
参数
val: 要在set容器中搜索的值。
返回值
如果值为val的元素存在于集合容器中,则返回1,否则返回0。
复杂度
大小的对数。
迭代器的有效性
没有变化。
数据竞争
可以访问容器。
并发访问集合中的元素是安全的。
异常安全的
如果抛出异常,容器中不会有任何更改。
示例1
让我们看一个简单的例子,用给定的键值搜索元素:
#include <iostream>
#include <set>
using namespace std;
int main()
{
// initialize container
set<int> mp;
// insert elements in random order
mp.insert(30);
mp.insert( 40 );
mp.insert( 60 );
mp.insert( 20);
mp.insert( 50 );
// checks if key 30 is present or not
if (mp.count(30))
cout << "The key 30 is present\n";
else
cout << "The key 30 is not present\n";
// checks if key 100 is present or not
if (mp.count(100))
cout << "The key 100 is present\n";
else
cout << "The key 100 is not present\n";
return 0;
}
输出:
The key 30 is present
The key 100 is not present
在上面的例子中,count()函数检查了给定的值。如果元素在集合容器中存在,则会显示该元素存在的消息,否则会显示该元素不存在的消息。
示例2
让我们看一个搜索集合元素的简单示例:
#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 << " is an element of myset.\n";
else
cout << " is not an element of myset.\n";
}
return 0;
}
输出:
a is an element of myset.
b is not an element of myset.
c is an element of myset.
d is not an element of myset.
e is not an element of myset.
f is an element of myset.
g is not an element of myset.
在上面的例子中,count()函数用于搜索集合中的’a’到’h’元素。
示例3
让我们看一个在集合中查找键的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> m = {'a','b','c','d'};
if (m.count('a') == 1) {
cout<< " 'a' is present in the set \n";
}
if (m.count('z') == 0) {
cout << " 'z' is not present in the set" << endl;
}
return 0;
}
输出:
'a' is present in the set
'z' is not present in the set
在上面的例子中,键’a’在集合m中存在,所以它的值是’a’的值,而键’z’在集合m中不存在,所以’z’没有值。
示例4
让我们看一个简单的例子:
#include <set>
#include <iostream>
int main()
{
using namespace std;
set<int> s1;
set<int>::size_type i;
s1.insert(1);
s1.insert(1);
// Keys must be unique in set, so duplicates are ignored
i = s1.count(1);
cout << "The number of elements in s1 with a sort key of 1 is: "
<< i << "." << endl;
i = s1.count(2);
cout << "The number of elements in s1 with a sort key of 2 is: "
<< i << "." << endl;
}
输出:
The number of elements in s1 with a sort key of 1 is: 1.
The number of elements in s1 with a sort key of 2 is: 0.