如何删除指向c ++的数组元素

时间:2016-11-23 03:16:55

标签: c++

我将一个字符数组传递给一个函数,并使用指针指向数组的第一个元素。 如何指向数组的每个元素并删除我不想要的字符。 我正在尝试使用括号和其他变量只是这个指针,也许是另一个。

感谢。

2 个答案:

答案 0 :(得分:0)

如果你真的想以你的方式去做,你必须声明一个新的字符数组,然后通过指针迭代数组来计算你想要留在数组上的字符的元素, count将是新数组的大小。

示例:

char b[] = "acbbca";
char* p = &b[0];
int oldsize = 6;
int newsize = 0;
for ( int a = 0; a < oldsize; a++ )
{
    if(*p!='b')
        newsize++; // increment the newsize when encountered non-b char
    p++;
}

在上面的代码段中,您计算​​非b字符的数量,因此它将是新数组的大小。

p = &b[0]; // point again to the first element of the array.
char newone[size]; declare the new array that will hold the result
int ctr = 0;
for ( int a = 0; a < oldsize; a++ )
{
    if(*p!='b')
    {
        newone[ctr] = *p; //store non-b characters
        ctr++;
    }
    p++;
}

在上面的代码段中,它将所有非b字符存储到新数组中。

另一种方法是使用std :: string。

std::string b = "aabbcc";
b.erase(std::remove(b.begin(),b.end(),'b'),b.end());

答案 1 :(得分:0)

由于数组无法调整大小,因此实际上没有“删除元素”这样的东西。要实际删除元素,您需要使用std::string之类的容器,其中实际上可以删除元素。

鉴于此,我们假设您只能使用数组,“删除”意味着将删除的值移动到数组的末尾,然后指向已删除元素的开始位置。 STL算法函数std::remove可用于实现此目的:

#include <iostream>
#include <algorithm>

int main()
{
    char letters[] = "aabbccbccd";

    // this will point to the first character of the sequence that is to be
    // removed.
    char *ptrStart = std::remove(std::begin(letters), std::end(letters), 'b');

    *ptrStart = '\0';  // null terminate this position
    std::cout << "The characters after erasing are: " << letters;
}

输出:

The characters after erasing are: aaccccd

Live Example

std::remove只接受您要删除的字符并将其放在数组的末尾。 std::remove的返回值是数组中的点 删除元素的位置。基本上,返回值指向丢弃元素的起始位置(即使元素实际上没有被丢弃)。

因此,如果您现在编写一个函数来执行此操作,它可能看起来像这样:

void erase_element(char *ptr, char erasechar)
{
   char *ptrStart = std::remove(ptr, ptr + strlen(ptr), erasechar);
   *ptrStart = '\0';  // null terminate this position
}

Live Example 2

我们传递指向第一个元素的指针,并使用strlen()函数来确定字符串的长度(函数假定字符串以空值终止)。

相关问题