當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ set::clear()用法及代碼示例

C++ STL set::clear() 函數

set::clear() 函數是一個預定義的函數,用於清除整個集合而不管其元素。

原型:

    set<T> st; //declaration
    st.clear()

參數:無需傳入

返回類型:

用法:該函數清除整個集合而不考慮其元素。

例:

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

    st.clear();  
    set content:
    empty set

要包含的頭文件:

    #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";
	if(st.empty()){
		cout<<"empty set\n";
		return;
	}
	for(it=st.begin();it!=st.end();it++)
		cout<<*it<<" ";
	cout<<endl;
}

int main(){
	cout<<"Example of clear 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

	cout<<"clearing all elements\n";
	st.clear();
	printSet(st);
	
	return 0;
}

輸出

Example of clear function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10
clearing all elements
Set contents are:
empty set  


相關用法


注:本文由純淨天空篩選整理自 set::clear() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。