c++数组中删除元素

比如说有数组char s1[] = {'a','b','c','d'}
删除‘b'后要变成acd
我用元素一个个前移,数组的大小如何减一呢? c++中数组的大小不是通过sizeof(s1)/sizeof(char)得来的吗?

//浮点数型数组(以double型数组为例)

intremoveGivenValue(double*pArray,constintnLen,constdoublelfGivenValue)

{

if(pArray==NULL||nLen<1)

return0;

intnValidLen=0;

for(inti=0;i<nLen;++i)

{

if(fabs(pArray[i]-lfGivenValue)<0.000001)

continue;

pArray[nValidLen++]=pArray[i];

}

returnnValidLen;

}

//整型数组

intremoveGivenValue(int*pArray,constintnLen,constintnGivenValue)

{

if(pArray==NULL||nLen<1)

return0;

intnValidLen=0;

for(inti=0;i<nLen;++i)

{

if(pArray[i]==nGivenValue)

continue;

pArray[nValidLen++]=pArray[i];

}

returnnValidLen;

}

扩展资料

C++数组指针用法

将a理解为指向数组头的一个指针,这样就好理解了。理解了之后确实好像豁然开朗的样子。这样a[5]就等于*(a+5),也就相当于将数组头指针向后推5个位置,然后取到该位置的数据了。

#include<iostream>

#include<typeinfo>

usingnamespacestd;

#definetype(a)typeid(a).name()

intmain(){

inta[10]={1,2,3,4,5,6,7,8,9,10};

cout<<"a="<<a<<"&a="<<&a<<endl;

int*p1=(int*)(&a+1);

int*p2=(int*)(a+1);

cout<<"*(p1-1)="<<*(p1-1)<<"*(p2-1)="<<*(p2-1)<<endl;

cout<<"sizeof(a)="<<sizeof(a)<<"sizeof(&a)="<<sizeof(&a)<<endl;

cout<<"TypeOf(a)="<<type(a)<<"TypeOf(&a)="<<type(&a)<<endl;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-03-19
你可以另外用一个变量标志你所需要的数组的大小,相当于数组中存放有意义数据的长度。数组定义之后大小是不能动态改变的。定义之后用sizeof(s1)/sizeof(char)计算的长度是固定不变的。在你的这个问题中,你可以在有意义的最后一个数据之后加一个'\0'起标识作用,然后用strlen()函数得到你要的长度。本回答被提问者和网友采纳
第2个回答  2013-10-28
学学用vector吧 创建个CHAR类型的vector 然后把数据放里就行 删除某一项的话直接删 然后vector就帮你做调整了
第3个回答  2013-10-27
用指针来指向元素‘b’,通过指针的移动,达到目的。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网