A
A
artur_agishev2020-11-11 14:42:46
C++ / C#
artur_agishev, 2020-11-11 14:42:46

How to remove array elements?

How to remove elements by index? For example, there are two indexes lr and it is necessary that the array does not contain elements from l to r inclusive. help me please

for (long long i = l - 1; i < r; ++i)			
  	s1[i] = s1[i + 1];

here is my code

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
Wataru, 2020-11-11
@artur_agishev

Good thing you should use std::vector. And he knows how to delete everything himself.

std::vector<int> a = {1, 2 ,3 ,4 ,5};
// Удалит элементы с l по r (l включительно, не удалит r).
// Если надо удалить r-ый элемент, то добавьте +1 во второй аргумент.
a.erase(a.begin()+l, a.begin()+r);

If you want to do it by hand, then you just need to see where the elements are moving. Those before l - do not move. Those from l to r disappear. Those after r are shifted to the left by r-l+1 positions.
for (i = l; i < n - 1 + l - r; ++i) {
  a[i] = a[i + r - l + 1];
}
// New length: n -1 + l - r;

A
Alexander Ananiev, 2020-11-11
@SaNNy32

https://stackoverflow.com/questions/879603/remove-...

A
Alexey, 2020-11-11
@resolut1123

Well, probably the easiest way will be to overwrite it in another array.
1. First you fill in the initial array.
2. you take a cycle from the filling, put the condition (Если i<l && r<n)n - the final number of the array into it, then add a counter of such elements, based on this counter it will be clear how many elements will be in the new array.
3. You declare a new array, for example, array[k], because in the last cycle the counter of such elements was k++.
4. With the same condition , you (Если i<l && r<n)already fill in the values ​​of the elements in the array.
Somehow, you may need to play around with the conditions, but I think the principle is clear. Sounds long, but it actually takes 5 minutes...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question