C ++ STL中的set :: size()函数

C ++ STL set::size()函数

set::size()函数是预定义的函数,用于获取集合的大小,它返回集合容器中元素的总数。

原型:

    set<T> st; //声明
    set<T>::iterator it; //迭代器声明
    int sz=st.size();

参数:无通过

返回类型:整数

用法:该函数返回集合的大小

示例

    For a set of integer,
    set<int> st;
    set<int>::iterator it;
    st.insert(4);
    st.insert(5);
    set content:
        4
        5

    int sz=st.size(); //sz =集合的大小为2-
    Print sz; //打印2-

包含的头文件:

    #include <iostream>
    #include <set>
    OR
    #include <bits/stdc++.h>

C ++实现:

#include <bits/stdc++.h>
using namespace std;

void printSet(set<int> st){
    set<int>:: iterator it;
    cout<<"Set contents are:\n";
    for(it=st.begin();it!=st.end();it++)
    cout<<*it<<" ";
    cout<<endl;
    
}

int main(){
    cout<<"Example of size function\n";
    set<int> st;
    set<int>:: iterator it;
    cout<<"inserting 4\n";
    st.insert(4);
    cout<<"inserting 6\n";
    st.insert(6);
    cout<<"inserting 10\n";
    st.insert(10);
    
    printSet(st); //打印当前设置
    
    //找到set sizeof-
    
    cout<<"current set size is: "<<st.size();
    
    return 0;
}

输出结果

Example of size function
inserting 4      
inserting 6      
inserting 10     
Set contents are:
4 6 10  
current set size is: 3