C++ empty()函数详解
empty()
函数是C++标准库中用于检查容器是否为空的成员函数之一。这个函数返回一个bool
类型的值,如果容器为空则返回true
,否则返回false
。本文将详细介绍empty()
函数的用法、示例代码以及输出。
使用方法
empty()
函数在各种STL容器中都有定义,比如vector
、list
、set
等。其使用方法非常简单,只需要在容器对象上调用该函数即可。下面是empty()
函数的通用语法:
container.empty();
其中container
代表需要检查是否为空的容器对象。
示例代码
接下来我们将通过几个示例代码来演示empty()
函数的使用。我们将分别以vector
、list
、set
这三种常见的容器为例。
示例1:使用vector
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
if(vec.empty()) {
std::cout << "The vector is empty" << std::endl;
} else {
std::cout << "The vector is not empty" << std::endl;
}
vec.push_back(10);
if(vec.empty()) {
std::cout << "The vector is empty" << std::endl;
} else {
std::cout << "The vector is not empty" << std::endl;
}
return 0;
}
运行结果:
The vector is empty
The vector is not empty
示例2:使用list
#include <iostream>
#include <list>
int main() {
std::list<int> myList;
if(myList.empty()) {
std::cout << "The list is empty" << std::endl;
} else {
std::cout << "The list is not empty" << std::endl;
}
myList.push_back(20);
if(myList.empty()) {
std::cout << "The list is empty" << std::endl;
} else {
std::cout << "The list is not empty" << std::endl;
}
return 0;
}
运行结果:
The list is empty
The list is not empty
示例3:使用set
#include <iostream>
#include <set>
int main() {
std::set<int> mySet;
if(mySet.empty()) {
std::cout << "The set is empty" << std::endl;
} else {
std::cout << "The set is not empty" << std::endl;
}
mySet.insert(30);
if(mySet.empty()) {
std::cout << "The set is empty" << std::endl;
} else {
std::cout << "The set is not empty" << std::endl;
}
return 0;
}
运行结果:
The set is empty
The set is not empty
总结
通过以上示例代码可以看出,empty()
函数是一个非常方便的函数,可以方便地检查容器是否为空。在实际编程中,我们经常需要根据容器是否为空来进行逻辑处理,empty()
函数正是为此而设计的。