我正在尝试编写一个函数removeOdds()来删除其数组参数中的所有奇数。该函数返回删除的项目数,如果数组最初为空,则返回-1。该函数有两个参数:
•将被修改的int数组
•数组的大小(使用size_t作为类型)
我不知道如何删除重复的evens?
int removeOdds(int a[], size_t size){
int count = 0;
int n = sizeof(a)/sizeof(a[0]);
if(!(n > 0)){
return -1;
}
for(size_t i = 0; i < size; i++){
if(a[i]%2 == 1){
a[i] = a[i+1];
count++;
}
}
size = count;
return count;
}
答案 0 :(得分:2)
static bool IsOdd (int i) { return ((i%2)==1); } /* Predicate function */
int removeOdds(int a[], size_t size)
{
if(0 == size) return -1; /* -1 if the array is initially empty */
/* Shift all the odd elements to the end */
int *new_end = std::remove_if (&a[0], &a[size], IsOdd); // #include <algorithm>
/* number of items removed */
return static_cast<int>(new_end - &a[0]);
}
在C++11
中,您可以使用更多花哨的lambda函数而不是IsOdd。