C++ 如何删除指向c++;

C++ 如何删除指向c++;,c++,C++,我将一个字符数组传递给函数,并使用指针指向数组的第一个元素。 如何指向数组的每个元素并删除不需要的字符。 我试图而不是使用括号和其他变量,只是这个指针,也许还有另一个指针 谢谢 如果确实想按自己的方式执行,则必须声明一个新的字符数组,然后通过指针在数组上迭代来计算要留在数组上的字符元素,该计数将是新数组的大小 p = &b[0]; // point again to the first element of the array. char newone[size]; declare th

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


谢谢

如果确实想按自己的方式执行,则必须声明一个新的字符数组,然后通过指针在数组上迭代来计算要留在数组上的字符元素,该计数将是新数组的大小

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++;
}
例如:

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++;
}

由于数组无法调整大小,所以实际上不存在“删除元素”这样的事情。要实际删除元素,您需要使用一个容器,如
std::string
,其中可以实际删除元素

鉴于此,我们假设您只能使用数组,“删除”意味着将删除的值移动到数组的末尾,然后指向删除的元素的起始位置。STL算法功能可用于完成以下任务:

#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;
}

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
}


我们传递一个指向第一个元素的指针,并使用
strlen()
函数确定字符串的长度(该函数假定字符串以null结尾)

“删除字符”是什么意思?数组的大小是固定的,因此不能删除条目。可以替换条目,但不能删除数组中的条目。如果您确实想要删除元素,那么使用容器,例如
std::string
。如果我有一个包含aabbccbccd元素的char数组,我想删除所有元素b。我使用指针指向数组的每个元素。。如何使用数组删除这些元素。我尽量不使用括号。如果您对元素的顺序没有任何顾虑,那么您只需在删除位置复制数组的当前最后一个元素,然后将数组的大小减少1。当然,在此之后,无论何时访问数组,数组大小都将发挥重要作用。从数组中“删除元素”不需要所有这些代码。您也不需要任何循环。STL算法函数,如
std::remove
可用于常规数组。
The characters after erasing are: aaccccd
void erase_element(char *ptr, char erasechar)
{
   char *ptrStart = std::remove(ptr, ptr + strlen(ptr), erasechar);
   *ptrStart = '\0';  // null terminate this position
}