动态从数组中删除元素并减小数组的大小 [英] Deleting element from array dynamically and reducing the size of the array

查看:113
本文介绍了动态从数组中删除元素并减小数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组,并且必须考虑数字12查找特定元素.如果数字12在数组中出现3次,那么我将必须删除所有出现的元素,然后减小数组的大小(因为这里发生12次3次并且数组的初始大小为10,那么现在删除12个数组后应该为7).是否可以通过这种方式动态减小数组的大小?您不能创建或使用新的数组.

解决方案

我不确定您实际使用的是哪种语言,但是在C ++中可以使用STL 向量 [集合之一 [std::vector而不是普通数组,则在C ++中很容易.

#include <vector>
#include <algorithm>
// this isn''t a complete program you could compile, just a code snippet
std::vector<int> myvec(10);
// let''s pretend myvec has been filled with suitable values, to remove any
// twelves:
myvec.erase(std::remove(myvec.begin(), myvec.end(), 12), myvec.end);


如果您真的不想使用std::vector,请使用 POD类型 [^ ],您可以使用重新分配 [

Suppose I have a array and have to search for a particular element consider number 12.if number 12 occurs in the array 3 times then I will have to delete all the occurences of the element and then reduce the size of the array(since here 12 occurs 3 times and initial size of array is 10 then now after deletion of 12 array size should be 7).Is it possible to reduce the size of an array in this way dynamically? You can''t create or use a new array.

解决方案

I''m not sure which language you are actually using but in C++ you could use the STL vector[^] class, which allows dynamic insertion and deletion. In Java you should probably use one of the Collections[^] classes.


It''s easy in C++ if you use a std::vector instead of a plain array.

#include <vector>
#include <algorithm>
// this isn''t a complete program you could compile, just a code snippet
std::vector<int> myvec(10);
// let''s pretend myvec has been filled with suitable values, to remove any
// twelves:
myvec.erase(std::remove(myvec.begin(), myvec.end(), 12), myvec.end);


If you really don''t want to use std::vector, for POD types[^] you can use realloc[^] to resize the array after removing an element.

Of course, under the hood realloc is often copying the array and invokes pretty much the same "magic" as vector, so I don''t know what you would really achieve with it, but it is an option.


这篇关于动态从数组中删除元素并减小数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆