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() { //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()函数检查给定值。如果元素存在于集合集合中,则它将显示消息,提示存在元素,否则不存在。
让我们看一个简单的示例来搜索集合的元素:
#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"元素。
让我们看一个简单的示例来搜索集合中的键:
#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"不出现在集合中,因此没有值" z"。
让我们看一个简单的例子:
#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.
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)