unordered_set::clear()函數是C++ STL中的內置函數,用於清除unordered_set容器。也就是說,此函數從unordered_set中刪除所有元素並將其清空。所有對容器的迭代器,指針和引用均無效。這將容器的大小減小到零。
用法:
unordered_set_name.clear()
參數:此函數不接受任何參數。
返回值:此函數不返回任何值。
以下示例程序旨在說明unordered_set::clear()函數:
程序1:
// C++ program to illustrate the
// unordered_set::clear() function
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<int> 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 << " ";
}
// clear the set
sampleSet.clear();
// size after clearing
cout << "\nSize of set after clearing elemets: "
<< sampleSet.size();
return 0;
}
輸出:
sampleSet contains: 25 5 10 15 20 Size of set after clearing elemets: 0
程序2:
// C++ program to illustrate the
// unordered_set::clear() function
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
unordered_set<string> 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 << " ";
}
// clear the set
sampleSet.clear();
// size after clearing
cout << "\nSize of set after clearing elemets: "
<< sampleSet.size();
return 0;
}
輸出:
sampleSet contains: Welcome To GeeksforGeeks For Geeks Computer Science Portal Size of set after clearing elemets: 0
相關用法
- C++ unordered_multimap clear()用法及代碼示例
- C++ multiset clear()用法及代碼示例
- C++ multimap clear()用法及代碼示例
- C++ ios clear()用法及代碼示例
- C++ unordered_multiset clear()用法及代碼示例
- C++ set::clear用法及代碼示例
- C++ map::clear()用法及代碼示例
- C++ unordered_map clear用法及代碼示例
- C++ list::clear()用法及代碼示例
- C++ std::string::clear用法及代碼示例
- C++ vector erase()、clear()用法及代碼示例
- C++ forward_list::clear()、forward_list::erase_after()用法及代碼示例
- C++ deque::clear()、deque::erase()用法及代碼示例
注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 unoredered_set clear() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。