C++ Set count()
C++ Set count()
C++ Set count()函数用于返回在容器中找到的元素数。由于set容器不包含任何重复元素,因此如果set容器中存在值val的元素,则此函数实际上返回1,否则返回0。
语法
size_type count (const value_type& val) const;
参数
val : 要在 Set 的容器中搜索的值。
返回值
如果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()函数检查给定值。如果元素存在于set容器中,则它将显示消息,指出元素存在,否则不存在。
示例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
在上面的示例中,集合m中存在键" a",因此它将是" a"的值,而集合中不存在键" z",因此,不存在值" 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.