从数组中删除零,并根据新的元素数量调整数组大小

Removing zeros from an array and resizing the array to the new amount of elements?

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

我在处理C++数组中的数据时遇到了另一个问题。我现在想通过删除数组中的所有零来抽取数组。

比如说,在我有array[4] = {1,2,0,0,4}之前,它会变成array[3] = {1,2,4}

我知道我需要使用for循环来迭代存储主数据的数组,并且我很可能需要初始化一个新数组来存储抽取的数据,但我不太确定如何进行

不能调整普通数组的大小,因为它是静态分配的。因此,最好使用标准库(STL)中的vector。这样一来,您就不需要创建新的数组。实际上,除非有充分的理由,否则通常使用std::vectorstd::array(在C++11中)比使用普通的类C数组要好。

通过使用vector,您可以执行以下操作:

std::vector<int> v{1,2,0,0,4};
v.erase(
    std::remove(v.begin(), v.end(), 0),
    v.end());

在擦除零元素之后,矢量仍然具有容量5(当然v.size()将返回3,正如预期的那样)。如果你可以使用C++11,那么你可以更进一步:

v.shrink_to_fit();

shrink_to_fit的调用将向量容纳它的容量减少到其中元素的实际数量(示例中为3)。这可能会节省内存(尤其是在向量中有许多元素的情况下)。

如果必须调整数组的大小,为什么不简单地使用std::vector。这个例子做到了。

#include <vector>
#include <algorithm>
bool isZero (int i) 
{
    return i == 0;
}
int main()
{
    std::vector<int> myarray;
    myarray.push_back( 0 );
    myarray.push_back( 1 );
    myarray.push_back( 0 );
    myarray.push_back( 3 );
    myarray.push_back( 9 );
    std::vector<int>::iterator newIter = std::remove_if( myarray.begin() , myarray.end() , isZero);
    myarray.resize( newIter -  myarray.begin() );
    return 0;
}

如果你不知道数组的内容,你就不知道有多少值将为非零,因此您的内存必须是动态的已分配。使用std::vector

std::vector<int> v;
std::copy_if(begin(array), end(array), std::back_inserter(v),
             [](int x) { return x != 0; });

如果您要从vector开始,您可以使用擦除删除操作数据。

v.erase(std::remove(begin(v), end(v), 0), end(v));

如果你真的想用艰苦的方式:

// count
auto non_zero_count = std::count_if(begin(array), end(array), 
                                    [](int x) { return x != 0;});
// allocate
int* new_array{new int[x]};
std::copy_if(begin(array), end(array), new_array,
             [](int x) { return x != 0; });

除非您知道所有的输入,否则这里并没有达到固定大小数组的解决方案。

假设你有一个数组,你想删除数组中的0值并调整它的大小。

int toResize[] = {4,3,2,0,8,7,9,0,5,4,7,0}; //12 elements
vector<int>resized;
vector<int>::iterator it;
for(int i=0;i<12;i++){
int check = toResize[i];
    if(check!=0){
     resized.push_back(check);
    }
}
for ( it=resized.begin() ; it < resized.end(); it++ )
cout << " " << *it;

如果您感到满意,请随时标记已回答的问题。