Home » C++ STL

set::empty() function in C++ STL

C++ STL set::empty() function: Here, we are going to learn about the empty() function of set in C++ STL (Standard Template Library).
Submitted by Radib Kar, on February 16, 2019

C++ STL set::empty() function

set::empty() function is a predefined function, it is used to check whether a set is empty or not. If set is empty it returns true (1), if set is not empty it returns false (0).

Prototype:

    set<T> st; //declaration
    set<T>::iterator it; //iterator declaration
    st.empty( ); 

Parameter: Nothing to pass

Return type: Bool (True or False)

Usage: The function checks whether the set is empty or not.

Example:

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

    Bool check=st.empty();  
    check =False

    St.erase(st.begin()); //erases 4
    St.erase(st.begin()); //erases 5
    Set content:
    Empty set 
    
    //now check again
    check=st.empty()
    check=TRUE

Header file to be included:

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

C++ implementation:

#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 empty 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); //printing current set

	if(st.empty())
	cout<<"It's empty\n";
	else
	cout<<"It's not empty\n";

	cout<<"erasing all elements\n";
	st.clear();
	
	if(st.empty())
		cout<<"It's empty\n";
	else
		cout<<"It's not empty\n";

	return 0;
}

Output

Example of empty function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10
It's not empty
erasing all elements
It's empty





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.