Since arrays cannot be resized, there really is no such thing as "removing elements". To actually remove elements, you would need to use a container such as std::string
where elements can actually be removed.
Given this, let's assume you can only use an array, and that "removal" means to move the removed values to the end of the array, and then point to where the removed elements start. The STL algorithm function std::remove can be used to accomplish this:
#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;
}
Output:
The characters after erasing are: aaccccd
Live Example
The std::remove
just takes the character you want to remove and places it at the end of the array. The return value of std::remove
is the point in the array
where the removed elements were placed. Basically the return value points to where the discarded elements start (even though the elements aren't actually discarded).
So if you now write a function to do this, it would probably look like this:
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
We pass a pointer to the first element, and use the strlen()
function to determine how long the string is (the function assumes the string is null-terminated).