How to delete even element in an array

let say if my array is

array[5]={2,3,4,5}

I want to delete all the even element in the array so that the output becomes

3,5
Looks to be the same question you've already asked.
https://www.cplusplus.com/forum/beginner/278105/

yeah, im looking for another method
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <algorithm>
#include <iterator>

int main() {
	int array[] {2, 3, 4, 5};

	std::copy(std::begin(array), std::remove_if(std::begin(array), std::end(array), [](const auto el) {return el % 2 == 0; }), std::ostream_iterator<int>(std::cout, " "));
}



3 5

yeah, im looking for another method

You could have asked there or at least shown what you already know and that you want something different.

It is not possible to change the size of an array.

The std::vector has two concepts: size and capacity.
The capacity is the size of the array.
The size is how many elements of the array are in use.
Therefore: size <= capacity

On int array[] {2, 3, 42, 4, 5}; size == capacity == 5.
After the "delete" the size must be 2 (but capacity remains 5) and the odd values must be at the first 'size' elements of the array.

The std::remove_if(std::begin(array), std::end(array), [](const auto el) {return el % 2 == 0; })
moves the odd values within the array and returns an iterator to one past last odd element.

It is possible to calculate the new 'size' from the returned iterator. See std::distance

The output after the "delete" must show only the 'size' first elements of the array, not the whole array.
The output after the "delete" must show only the 'size' first elements of the array, not the whole array.


That's what copy() does - as it takes its end iterator as the one returned by remove_if() - and why I used copy() rather than a for loop! :)

Or using distance and a for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <algorithm>
#include <iterator>

int main() {
	int array[] {2, 3, 4, 5};

	const auto newsz {std::distance(std::begin(array), std::remove_if(std::begin(array), std::end(array), [](const auto el) {return el % 2 == 0; }))};

	for (size_t i = 0; i < newsz; ++i)
		std::cout << array[i] << ' ';

	std::cout << '\n';
}

Last edited on
yeah, im looking for another method

Yet another one is to create a parallel array to the one in question and store a flag against each corresponding item to indicate whether it is deleted or not. The actual data is not removed/deleted.

It's another way but STL containers are there to be used.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <valarray>
using namespace std;

int main()
{
   valarray<int> A{ 2, 3, 4, 5 };
   A = valarray<int>( A[A%2 == 1] );
   for ( int e : A ) cout << e << ' ';
}


It's easier in other languages.
Topic archived. No new replies allowed.