So I've currently been studying C++ independently for a couple weeks with the help of good old books. One of the exercises was to make a "games library" where you can see your list of games, add a title, or delete it (has nothing to do with games). The catch is that it has to use Vectors and Iterators, which I would think makes it easier. Here's what I have:

//Games Library

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

int main(){

	vector<string>games;
	vector<string>::iterator iter;
	string choice;
	string gameAdd;
	int gameDelete;
	int i;

	cout<<"Welcome to your games library!"<<endl;
	cout<<"\nWhat would you like to do?"<<endl;
	cout<<"Type 'add' to add a game"<<endl;
	cout<<"Type 'remove' to remove a game"<<endl;
	cout<<"Type 'quit' to end the program\n"<<endl;

	while(choice!="quit"){
		cout<<"Games:"<<endl;
		i=1;
		for(iter=games.begin();iter!=games.end();iter++,i++){ //Displays Game list
			cout<<i<<"- "<<*iter<<endl;
		}
		cout<<"\nChoice:";
		cin>>choice;
		if(choice=="add"){
			cout<<"What is it's name(no spaces)? ";
			cin>>gameAdd;
			games.push_back(gameAdd);
	}
		else if(choice=="remove"){
			cout<<"What number is the game associated with? ";
			cin>>gameDelete;
			games.erase(games.begin()+(gameDelete-1));//Deletes game using iterators, at space "gameDelete" (-1 because list starts at 0)
		}
		else if(choice!="quit"){
			cout<<"Invalid choice"<<endl;
		}
	}
	cout<<"\nGoodbye!"<<endl;
	return 0;
	

}

I feel like the 'adding' feature is pretty straight forward, but my 'remove' feels wildly inefficient. Some help neatening up would be very much appreciated. If this post violates any conventions of the site, I apologize; I'm new.

Recommended Answers

All 4 Replies

Not exactly sure why you have that -1 there.. what happens when the vector is already of size one? then what? it'll delete nothing or crash if it's empty. Do some checks and see how it turns out.

I'm not sure why you think that it is inefficient. That is how you delete something from a vector.
I would do some checks on the input, however. If the user enters anything less than 1 or greater than the size of your vector you are going to have trouble.

Thanks guys; I'll see what I can do

ok, so I just threw in this loop:

while(gameDelete>games.size()||gameDelete<1){
        cout<<"What number is the game associated with? ";
	cin>>gameDelete;
			}

If that's all, then thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.