Deleting/Replacing an element from an array

I'm making a program that takes in names, and lists them.
For example;
sNames[1] = "Bob";
sNames[2] = "Jim";
sNames[3] = "Kyle";
sNames[4] = "Tim";
sNames[5] = ""

So lets say I don't want Jim anymore. How could I make a function that will make him disappear? Since I'm a beginner at coding, I can code what I mean, so I'll just put pseudo code.

//Function name (string variable)
//Loop that checks for Jim's name
//Makes Jims name become Kyles (therefore "deleting" Jim)
//Makes Tim become Kyle
//Makes "" become Tim
//Close loop and function

So basically whats left over is.
sNames[1] = "Bob";
sNames[2] = "Kyle";
sNames[3] = "Tim";
sNames[4] = ""

So can anyone help me put my pseudo code into actually code?
OK the key to understanding the code below is this bit of code here.
1
2
3
4
5
6
7
8
9
10
// Move found entry into index[0]
	string temp = names[index];
	names[index] = names[0];
	names[0] = temp;

	// Move everything up in the array one position
	 for(int i = 1; i < size; i++)
	 {
		  names[i -1] = names[i];
	 }

If you notice the first chunk of code is taking the entry you have located and moving it to position 0.
This is is because when in the next piece of code if you move everything up in the array the information in position [0] is lost. This is because of the body of the for loop. Ask if you have questions. Hopefully this is what you are trying to solve.






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
using namespace std;

int findAndRemove(string names[], int& size)
{
	string name1;
	int index = 0;
	bool found = false;
	
	//User prompt
	cout << "Enter name to be deleted " << endl;
	cin >> name1;
	
	
	//Find name
	while( index < size && !found )
	{
	  if(names[index].compare(name1)== 0)
	  {
		 found = true;
	  }
		else if(!found)
		index++;
	}
	
	// Move found entry into index[0]
	string temp = names[index];
	names[index] = names[0];
	names[0] = temp;

	// Move everything up in the array one position
	 for(int i = 1; i < size; i++)
	 {
		  names[i -1] = names[i];
	 }

	  return size - 1;

}

int main()
{
	
	string names[]= {"Bob","Jim","Kyle", "Tim"};
	int size = 4;
	int newSize = 0;

	//To see before
	for( int i = 0; i < size; i ++)
	{
		cout << names[i] << " " ;
	}
	cout << endl;

newSize = findAndRemove(names, size);

// To see array after
for( int i = 0; i < newSize; i ++)
	{
		cout << names[i] << " " ;
	}

	system("PAUSE");
	return 0 ;
}
Anyway I suggest using vectors, not arrays. Vectors have methods that fit your needs better than array.
Check out:

vector<string> Names;

Names.push_back
Names.delete

http://www.cplusplus.com/reference/vector/vector/
Topic archived. No new replies allowed.