/*
* @Abstract : 去除数组中的特定值
* @Crete Date : 11/10/2018.
* @Author : shaoguang.
*/
#include <math.h> // fabs
/**
* @param pArray : 要去除数据的原数组。
* @param nLen : 要去除数据的原数组的元素个数。
* @param lfValue : 要从数组中去掉的值。
*
* @return : 去除数据后的数组有效元素个数。
*
* @note : 数组实际元素个数并没有改变。
*/
// 浮点数型数组(以double型数组为例)
int removeGivenValue(double *pArray, const int nLen, const double lfGivenValue)
{
if (pArray == NULL || nLen < 1)
return 0;
int nValidLen = 0;
for (int i = 0; i < nLen; ++i)
{
if (fabs(pArray[i] - lfGivenValue) < 0.000001)
continue;
pArray[nValidLen++] = pArray[i];
}
return nValidLen;
}
// 整型数组
int removeGivenValue(int *pArray, const int nLen, const int nGivenValue)
{
if (pArray == NULL || nLen < 1)
return 0;
int nValidLen = 0;
for (int i = 0; i < nLen; ++i)
{
if (pArray[i] == nGivenValue)
continue;
pArray[nValidLen++] = pArray[i];
}
return nValidLen;
}
当然,不用返回值的方式取接收数组有效元素个数也行,直接传入实际元素个数的地址(或者引用)也行。如果实际情况不需要知道函数执行后数组实际元素的个数,这种方法无疑更好。
// 变体
void removeGivenValue(double *pArray, int *pLen, const double lfGivenValue)
{
if (pArray == NULL || || pLen == NULL || *pLen < 1)
return;
int nValidLen = 0;
for (int i = 0; i < *pLen; ++i)
{
if (fabs(pArray[i] - lfGivenValue) < 0.000001)
continue;
pArray[nValidLen++] = pArray[i];
}
*pLen = nValidLen;
}