C++中判断vector是否为空
时间: 2023-09-20 20:03:15 浏览: 320
在C++中,可以使用`empty()`函数来判断一个`vector`是否为空。`empty()`函数返回一个布尔值,如果`vector`为空,则返回`true`,否则返回`false`。
以下是一个示例代码:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
if(myVector.empty()) {
std::cout << "Vector is empty." << std::endl;
} else {
std::cout << "Vector is not empty." << std::endl;
}
return 0;
}
```
输出结果将是:"Vector is empty.",因为在示例代码中,`myVector`是一个空的`vector`。
相关问题
c++判断vector是否为空
在C++中,可以使用vector的empty()函数来判断一个vector是否为空。如果vector为空,则empty()函数返回true,否则返回false。例如,可以使用以下代码来判断一个名为vec的vector是否为空:
```
if (vec.empty()) {
// vector为空
} else {
// vector不为空
}
```
另外,还可以使用vector的size()函数来获取vector中元素的数量,如果size()函数返回0,则说明vector为空。但是,推荐使用empty()函数来判断vector是否为空,因为empty()函数的效率更高。
c++判断vector不为空
可以使用 vector 的 `empty()` 函数来判断 vector 是否为空。如果 vector 为空,则该函数返回 true,否则返回 false。例如:
```cpp
#include <vector>
#include <iostream>
int main() {
std::vector<int> myvector;
if (myvector.empty()) {
std::cout << "myvector is empty." << std::endl;
} else {
std::cout << "myvector is not empty." << std::endl;
}
return 0;
}
```
如果 vector 是空的,输出将是:
```
myvector is empty.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)