📅  最后修改于: 2020-10-20 08:07:31             🧑  作者: Mango
C++ set count()函数用于返回在容器中找到的元素数。由于set容器不包含任何重复元素,因此如果set容器中存在值val的元素,则此函数实际上返回1,否则返回0。
size_type count (const value_type& val) const;
val:要在集合容器中搜索的值。
如果set容器中存在值val的元素,则返回1,否则返回0。
大小为对数。
没有变化。
容器被访问。
同时访问集合的元素是安全的。
如果引发异常,则容器中没有任何更改。
让我们看一个简单的示例,使用给定的键值搜索元素:
#include
#include
using namespace std;
int main()
{
// initialize container
set 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()函数检查给定值。如果元素存在于集合容器中,则它将显示消息,指出存在元素,否则不存在。
让我们看一个简单的示例来搜索集合的元素:
#include
#include
using namespace std;
int main ()
{
set 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”元素。
让我们看一个简单的示例来搜索集合中的键:
#include
#include
using namespace std;
int main(void) {
set 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”不出现在集合中,因此没有值“ z”。
让我们看一个简单的例子:
#include
#include
int main()
{
using namespace std;
set s1;
set::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.