c++中empty怎么使用
时间: 2024-04-08 14:32:57 浏览: 28
在C++中,`empty()` 是一个成员函数,用于检查容器是否为空。不同的容器类型有不同的用法。以下是几个常见容器的 `empty()` 的用法示例:
1. std::vector:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums;
if (nums.empty()) {
std::cout << "Vector is empty" << std::endl;
} else {
std::cout << "Vector is not empty" << std::endl;
}
return 0;
}
```
2. std::string:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
if (str.empty()) {
std::cout << "String is empty" << std::endl;
} else {
std::cout << "String is not empty" << std::endl;
}
return 0;
}
```
3. std::stack:
```cpp
#include <iostream>
#include <stack>
int main() {
std::stack<int> st;
if (st.empty()) {
std::cout << "Stack is empty" << std::endl;
} else {
std::cout << "Stack is not empty" << std::endl;
}
return 0;
}
```
在上述示例中,我们使用了不同类型的容器(std::vector、std::string、std::stack)并调用了它们的 `empty()` 函数来判断容器是否为空。如果容器为空,我们输出相应的提示信息。否则,输出不为空的提示信息。
请注意,每个容器类型都有其自己的成员函数,用于检查容器是否为空,因此使用时要根据对应容器的类型选择正确的函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)