unordered_set :: count()函数是C++ STL中的内置函数,用于对unordered_set容器中特定元素的出现进行计数。由于unordered_set容器不允许存储重复的元素,因此该函数通常用于检查容器中是否存在元素。如果元素存在于容器中,则该函数返回1,否则返回0。
语法:
unordered_set_name.count(element)
参数:此函数接受单个参数元素。此参数表示容器中是否存在需要检查的元素。
返回值:如果元素存在于容器中,则此函数返回1,否则返回0。
下面的程序说明了unordered_set :: count()函数:
程序1 :
// CPP program to illustrate the
// unordered_set::count() function
#include
#include
using namespace std;
int main()
{
unordered_set sampleSet;
// Inserting elements
sampleSet.insert(5);
sampleSet.insert(10);
sampleSet.insert(15);
sampleSet.insert(20);
sampleSet.insert(25);
// displaying all elements of sampleSet
cout << "sampleSet contains: ";
for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
cout << *itr << " ";
}
// checking if element 20 is present in the set
if (sampleSet.count(20) == 1) {
cout << "\nElement 20 is present in the set";
}
else {
cout << "\nElement 20 is not present in the set";
}
return 0;
}
输出:
sampleSet contains: 25 5 10 15 20
Element 20 is present in the set
程序2 :
// C++ program to illustrate the
// unordered_set::count() function
#include
#include
using namespace std;
int main()
{
unordered_set sampleSet;
// Inserting elements
sampleSet.insert("Welcome");
sampleSet.insert("To");
sampleSet.insert("GeeksforGeeks");
sampleSet.insert("Computer Science Portal");
sampleSet.insert("For Geeks");
// displaying all elements of sampleSet
cout << "sampleSet contains: ";
for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
cout << *itr << " ";
}
// checking if element GeeksforGeeks is
// present in the set
if (sampleSet.count("GeeksforGeeks") == 1) {
cout << "\nGeeksforGeeks is present in the set";
}
else {
cout << "\nGeeksforGeeks is not present in the set";
}
return 0;
}
输出:
sampleSet contains: Welcome To GeeksforGeeks For Geeks Computer Science Portal
GeeksforGeeks is present in the set
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。