C++中,如何将一个数组清空
时间: 2024-03-26 07:42:00 浏览: 89
在C++中,可以使用以下两种方法清空数组:
1. 使用memset函数将数组中的所有元素设置为0:
```c++
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
memset(arr, 0, sizeof(arr));
```
2. 使用循环将数组中的所有元素设置为0:
```c++
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(int i = 0; i < 10; i++){
arr[i] = 0;
}
```
无论使用哪种方法,都可以将数组中的所有元素清空。
相关问题
c++怎么将一个vector动态数组清空
可以使用vector的clear()方法来清空一个动态数组。该方法会将vector中的所有元素清空,使其变为空vector。具体用法如下:
vector<int> vec;
// 向vec中添加元素
vec.clear(); // 清空vec
需要注意的是,clear()方法只是清空vector中的元素,并不会释放vector所占用的内存空间。如果需要释放内存空间,可以使用swap()方法,将vector与一个空vector交换,从而释放内存空间。具体用法如下:
vector<int>().swap(vec); // 释放vec占用的内存空间
C++中,如何将std::vector<std::string> result这个数组清空
在C++中,可以使用以下两种方法清空 `std::vector<std::string>` 数组:
1. 使用`clear()`函数清空:
```c++
std::vector<std::string> result;
// 向 result 中添加一些元素
result.clear(); // 清空 result 数组
```
2. 使用`resize()`函数清空:
```c++
std::vector<std::string> result;
// 向 result 中添加一些元素
result.resize(0); // 清空 result 数组
```
无论使用哪种方法,都可以将 `std::vector<std::string>` 数组清空。建议使用 `clear()` 函数来清空 `std::vector` 数组,因为它更加简洁明了。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)