C ++ empty()函數(shù)的作用是:檢查集合容器是否為空。如果集合容器為空(size為0),則返回true,否則返回false。
bool empty() const; // 直到 C++ 11 bool empty const noexcept; //從 C++ 11 開始
沒(méi)有
它返回真如果設(shè)定的容器是空的(大小為0),否則返回假。
不變。
沒(méi)有變化。
容器被訪問(wèn)。
同時(shí)訪問(wèn)set的元素是安全的。
此函數(shù)永遠(yuǎn)不會(huì)引發(fā)異常。
讓我們看一個(gè)簡(jiǎn)單的示例,以檢查集合是否包含任何元素:
#include <set>
#include <iostream>
using namespace std;
int main()
{
set<int> numbers;
cout << " 最初,numbers.empty (): " << numbers.empty() << "\n";
numbers = {100, 200, 300};
cout << "\n 添加元素之后,numbers.empty(): " << numbers.empty() << "\n";
}輸出:
最初,numbers.empty (): 1 添加元素之后,numbers.empty(): 0
在上面的示例中,set的初始大小為0,因此,empty()函數(shù)返回1(true),在添加元素后返回0(false)。
讓我們看一個(gè)簡(jiǎn)單的示例來(lái)檢查set是否為空:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> s;
if (s.empty())
cout << "集合是空的。" << endl;
s = {100};
if (!s.empty())
cout << "集合不是空的。" << endl;
return 0;
}輸出:
集合是空的。 集合不是空的。
在上面的實(shí)例中,使用了if條件語(yǔ)句。如果set為空,則在添加元素后返回set為空;如果set為空,則在添加元素后返回set非空。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset;
myset = {100, 200, 300};
while (!myset.empty())
{
cout << *myset.begin()<< '\n';
myset.erase(*myset.begin());
}
return 0;
}輸出:
100 200 300
在上面的示例中,它僅在while循環(huán)中使用empty()函數(shù)并打印set的元素,直到set不為空。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
typedef set<int> phoneSet;
int number;
phoneSet phone;
if (phone.empty())
cout << "集合為空。 請(qǐng)插入內(nèi)容! \n " << endl;
cout<<"輸入三組數(shù)字: \n";
for(int i =0; i<3; i++)
{
cin>> number; // 獲得值
phone.insert(number); //插入數(shù)據(jù)到set
}
if (!phone.empty())
{
cout<<"\n電話號(hào)碼列表: \n";
phoneSet::iterator p;
for(p = phone.begin(); p!=phone.end(); p++)
{
cout<<(*p)<<" \n ";
}
}
return 0;
}輸出:
集為空。 請(qǐng)插入內(nèi)容! 輸入三組數(shù)字: 1111 5555 3333 電話號(hào)碼列表: 1111 3333 5555
在上面的示例中,該程序首先使用三組數(shù)字交互創(chuàng)建電話機(jī),然后檢查該電話機(jī)是否為空。如果set為空,則顯示一條消息,否則,顯示set中所有可用的電話號(hào)碼。