C++ set size()函数用于查找set集合中存在的元素数。
成员类型 size_type 是无符号整数类型。
size_type size() const; //until C++ 11 size_type size() const noexcept; //since C++ 11
它返回集合中存在的元素数。
让我们看一个简单的例子来计算集合的大小:
#include <set> #include <iostream> using namespace std; int main() { set<char> num {'a', 'b', 'c', 'd'}; cout << "num set contains " << num.size() << " elements.\n"; return 0; }
输出:
num set contains 4 elements.
在上面的示例中,set num包含4个元素。因此,size()返回4个元素。
让我们看一个简单的示例,计算集合的初始大小和添加元素后的集合大小:
#include <iostream> #include <set> using namespace std; int main(void) { set<int> m; cout << "Initial size of set = " << m.size() << endl; m = {1,2,3,4,5,6}; cout << "Size of set after inserting elements = " << m.size() << endl; return 0; }
输出:
Initial size of set = 0 Size of set after inserting elements = 6
在上面的示例中,第一个集合为空,因此,size()函数将返回0,在插入6个元素后将返回6。
让我们看一个简单的例子:
#include <iostream> #include <set> using namespace std; int main () { set<int> myset = {100,200,300,400}; while (myset.size()) { cout << *myset.begin()<< '\n'; myset.erase(myset.begin()); } return 0; }
输出:
100 200 300 400
在上面的示例中,它仅在while循环中使用size()函数并打印set的元素,直到set的大小为止。
让我们看一个简单的例子:
#include <iostream> #include <set> #include <string> using namespace std; int main() { typedef set<int> marksSet; int number; marksSet marks; cout<<"Enter three sets of marks: \n"; for(int i =0; i<3; i++) { cin>> number; //Get value marks.insert(number); //Put them in set } cout<<"\nSize of phone set is:"<< marks.size(); cout<<"\nList of telephone numbers: \n"; marksSet::iterator p; for(p = marks.begin(); p!=marks.end(); p++) { cout<<(*p)<<" \n "; } return 0; }
输出:
Enter three sets of marks: 78 90 84 Size of phone set is: 3 List of telephone numbers: 78 84 90
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)