如何清除数组中的元素
How to clear out element inside an array?
我想清除数组中的所有元素,但我不知道如何自动清除它。 有它的功能吗?喜欢列表的 clear((??
int array[5] = {2,5,4,8,6};
然后我想清除所有内容并添加一组新值
您的问题无效,因为您无法clear out
数组。数组具有固定大小,并且总会有一些值。
如果要重用数组,只需覆盖现有值即可。
也许考虑使用std::vector
。使用clear()
函数,您可以清除std::vector
中的所有值。
在此处了解std::vector
清除数组意味着将所有值设置为 T((,对于基本算术类型的数组,这些值等效于将所有元素设置为零。
您可以通过多种方式做到这一点。第一种是使用在标头<cstring>
中声明的标准 C 函数std::memset
。例如
#include <iostream>
#include <cstring>
int main()
{
int array[] = { 2, 5, 4, 8, 6 };
const size_t N = sizeof( array ) / sizeof( *array );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
std::memset( array, 0, N * sizeof( int ) );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
另一种方法是使用在标头<algorithm>
中声明的标准算法std::fill
。例如
#include <iostream>
#include <algorithm>
int main()
{
int array[] = { 2, 5, 4, 8, 6 };
const size_t N = sizeof( array ) / sizeof( *array );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
std::fill( array, array + N, 0 );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
在这两种情况下,程序输出都是
2 5 4 8 6
0 0 0 0 0
如果您需要可变长度数组,请使用标准容器std::vector<int>
。
例如
#include <iostream>
#include <iomanip>
#include <vector>
int main()
{
std::vector<int> array = { 2, 5, 4, 8, 6 };
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
array.clear();
std::cout << "array is empty - " << std::boolalpha << array.empty() << std::endl;
return 0;
}
程序输出为
2 5 4 8 6
array is empty - true
除了array.clear();
还可以在程序中使用array.resize( 0 );
。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 通过交换元素使数组相同
- 查找包含 N 个元素的数组的最小值和最大值
- 从用户输入中删除数组
- 逐个元素检测数组中的更改
- 如何让用户C++输入少于 10 个元素的数组
- 如何将输入到具有未知数量元素的数组中?
- 按元素添加元组
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 为什么我不能将元素插入数组中的列表?
- 我有一个包含几个重复元素的数组,我想找到最接近数组末尾的重复元素的索引
- 在未分配某些元素的数组中存储了什么值
- 最长的子序列,其元素构成一组递增的整数
- C++向量元组,请按索引从元素创建元组
- 删除向量而不删除数组
- 使用 stl::map 和 stl::unordered_map 对包含大量重复元素的数组数据进行排序
- 如何清除数组中的元素
- 清除数组时如何使用模数
- 在C++中清除数组会在外部函数中而不是在main()中产生编译器错误
- 最有效的方法来清除数组的向量