c++把数组所有元素剔除_C++如何去除数组中的特定值(删除数组中特定的元素)?...

这篇博客介绍了一个C++函数,用于从浮点数和整数数组中删除特定值。函数`removeGivenValue`根据传入的值,遍历数组并跳过相等的元素,保留不同值。它返回去除特定值后的有效元素个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*

* @Abstract: 去除数组中的特定值

* @Crete Date : 11/10/2018.

* @Author: shaoguang.

*/

#include // 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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值