[英]My code isn't shifting the elements to right, want to delete specific elements from array and shift them to right?
//method to delete specific elements in range and shift to right int deleteAll(int start, int end) { for(int i = start; i<=end; i++){ arr[i]=0; for(int j = i; j<counter; j++){ arr[j]=arr[j+1]; cout<<arr[i]; } counter --; }
如果你允許,我有一些時間要提一下:
arr[i] = 0
因為我們在它之后立即分配另一個值(緊接着,在內部循環中我們將arr[j]
分配給arr[j + 1]
當j = i
)。我想,這就是您要搜索的內容:
int deleteAll (int start, int end)
{
int shift = end - start,
i_lim = counter - shift;
for(int i = start; i < i_lim; i++)
arr[i] = arr[i + shift];
// the following loop is necessary only if you want
// to reset the last elements of the array
int null_value = 0; // <- you can put anything you like here
for(i = i_lim; i < counter; j++)
arr[i] = null_value;
// new length is shorter:
counter -= shift;
}
為了提高效率,您可以將int start
更改為(在某些 C++ 實現中緊湊兩倍) unsigned short int start
。 int end
也是如此。 祝你有美好的一天! =)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.