Function to remove an array element

Hey all, I'm trying to write a function to call to main that will remove a string element in a user input array.

This is the code I currently have for the function:
1
2
3
4
5
6
7
8
9
10
11
12
void removeName(string remove, string array[], int size)
{
	cout << "Which name would you like to remove? ";
	cin >> remove;
	for (int i = 0; i < size; i++)
	{
		if (array[i] == remove)
		{
			array[i-1];
		}
	}
}


And this is the call to main:
 
removeName(remove, names, size);


I don't need to run this to know it doesn't work (but I tested it anyway and it doesn't), but I'm not sure how to fix it. I know it needs to change the array somehow. I tried using the function:

void removeName(string remove, string& array[], int size)

But got a "creating array of references" error, and no idea what that is. Is anyone able to help or suggest something to try?

Thanks~
Last edited on
You cannot (and you don't need to) create an array of references. The & sign means reference in this context.

What you need is add a bool variable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void removeName(string remove, string array[], int &size)
// Note: size must be decreased if found, hence you pass it as a reference
{
	cout << "Which name would you like to remove? ";
	cin >> remove;

	bool is_found = false; // Note

	for (int i = 0; i < size; i++)
	{
		// Note:
		if(is_found)
			array[i-1] = array[i];
		else if (array[i] == remove)
			is_found = true;
	}

	if(is_found)
		--size; // Note: since it's passed as a reference the callers (in main) variable is modified

}
Thank you coder, it worked! Theoretically, would the same base syntax work for adding an element to an array, but replace array[i-1] with array[i+1] and replace --i with ++i?
Just replacing wouldn't suffice. You need to move the elements from the last index (size - 1) until the the index in question. And you need to make sure that array is large enough to hold the additional element.
Topic archived. No new replies allowed.