从数组中删除零,并根据新的元素数量调整数组大小
Removing zeros from an array and resizing the array to the new amount of elements?
我在处理C++数组中的数据时遇到了另一个问题。我现在想通过删除数组中的所有零来抽取数组。
比如说,在我有array[4] = {1,2,0,0,4}
之前,它会变成array[3] = {1,2,4}
。
我知道我需要使用for循环来迭代存储主数据的数组,并且我很可能需要初始化一个新数组来存储抽取的数据,但我不太确定如何进行
不能调整普通数组的大小,因为它是静态分配的。因此,最好使用标准库(STL)中的vector
。这样一来,您就不需要创建新的数组。实际上,除非有充分的理由,否则通常使用std::vector
或std::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;
如果您感到满意,请随时标记已回答的问题。
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int