如何清除数组中的元素

How to clear out element inside an array?

本文关键字:元素 清除数组      更新时间:2023-10-16

我想清除数组中的所有元素,但我不知道如何自动清除它。 有它的功能吗?喜欢列表的 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 );