Deleting an element from a vector through user input

Hello, have been learning c++ for the past week and the book that i'm reading has given me a task in which I have to maintain a list of games, allow the user to list all titles, add titles, and remove titles. The only one I can't figure out is removing titles. I already know about vector.pop_back() but it only removes the last element in the vector, and what i'm trying to do is make it to where I can remove a certain element that has already been added to the list through user input. Heres the coding:

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
// Video Game List
// Stores A List of User's Games

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
	vector<string>::const_iterator iter;
	vector<string> list;
	string addGame;
	string removeGame;
	
	cout << "\t\tWelcome to the Video Game List" << endl;
	cout << "\n1 - Add a game to the list" << endl;
	cout << "\n2 - Remove the last game entered on the list" << endl;
	cout << "\n3 - View current list" << endl;
	cout << "\nEnter any other number to leave" << endl;

	while (true)
	{

	int choice = 1;
	cout << "\nWhat do you want to do?" << endl;
	cin >> choice;
	
	switch (choice)
	{
	case 1:
		cout << "\nType the name of the game you wish to add to the list" << endl;
		cin >> addGame;

		list.push_back(addGame);
		cout << "\n'" << addGame << "' has been added to the list" << endl;
		
		break;
	case 2:
		cout << "\nType the name of the game you wish to remove from the list" << endl;
		
		cout << "\n'" << removeGame << "' has been removed from the list" << endl;
		
		break;
	case 3:
		if (list.size() <= 0)
			cout << "You don't have anything on the list!" << endl;
		else
			cout << "\nThe current list:\n" << endl;
		for (iter = list.begin(); iter != list.end(); ++iter)
			cout << *iter << endl;

		break;
	default:
		cout << "\nGoodbye." << endl;
	} 
	}
	
	cin.ignore(cin.rdbuf()->in_avail() + 1);
	return 0;
}
vector.erase() should be able to accomplish what you want. For example..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
case 2:
	cout << "\nType the name of the game you wish to remove from the list" << endl;
	cin >> removeGame;

	for (iter = list.begin(); iter != list.end(); iter++)  // loops through list
	{
		if(*iter == removeGame)
		{
			list.erase(iter);  // Erases the user entered word if found
			cout << "\n'" << removeGame << "' has been removed from the list" << endl;
			break;   // stops looping 
		}
			
		if(iter == list.end() - 1)  // If the word isn't found by the end of the list 
		{
			cout << "Game not found" << endl; 
		}
	}

	break;
Last edited on
Thanks man it worked.
Topic archived. No new replies allowed.