1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
// remove all occurrences of value in the array of logical size n.
// return the new logical size of the array after removal
// complexity: exactly one pass through the array
std::size_t remove( int* array, std::size_t n, int value ) {
// get to the first occurrence of value
// (we don't need to move anything before this)
std::size_t pos = 0 ;
for( ; pos < n && array[pos] != value ; ++pos ) ;
if( pos == n ) return n ; // not found; there is nothing to remove
// now, make one pass from pos+1 up to the end of the array,
// moving the non-removed elements to the left
// the target position of the next element which is not removed
std::size_t move_to = pos ;
for( std::size_t i = pos ; i++ < n ; ) // from pos+1 up to the end of the array
if( array[i] != value ) array[move_to++] = array[i] ;
return move_to-1 ; // return the new logical end of the array
}
int main() {
int a[] { 2, 1, 3, 2, 5, 2, 7, 8, 4, 9, 2, 4, 3, 7, 6 } ;
auto sz = sizeof(a) / sizeof(*a) ;
std::cout << "original array: [ " ;
for( std::size_t i = 0 ; i < sz ; ++i ) std::cout << a[i] << ' ' ;
std::cout << "] size: " << sz << '\n' ;
for( int v : { 6, 2, 7, 1, 9, 4, 0 } ) {
sz = remove( a, sz, v ) ;
std::cout << "after remove " << v << ": [ " ;
for( std::size_t i = 0 ; i < sz ; ++i ) std::cout << a[i] << ' ' ;
std::cout << "] size: " << sz << '\n' ;
}
}
|