ICT Learning Centre
Sample code for adding and removing items from a vector
Written by James Murphy on 2009-10-20
 
#include <iostream>
#include <vector>
#include <string>
#include <conio.h>
using namespace std;

// Simple item class
class item {
public:
	string name;
	int value;
	item() {
		name = "";
		value = 0;
	}
	item(string s, int v) {
		name = s;
		value = v;
	};
};

// Simple player class
class player {
public:
	vector<item*> inventory;
	void pickup(item* i) {
		inventory.push_back(i);
	}
};

int main() {

	// Create a new item
	item* item1 = new item("Carrot", 5);

	// Create a new inventory vector
	vector<item*> inventory;

	// Add the item to the end of the inventory vector
	inventory.push_back(item1);

	// What is the size of the vector? (How many elements does it have?)
	int sz = inventory.size();

	// Loop through the vector outputting a position and details 
        // of the item to the screen
	for(int i=0;i<sz;i++) {
		cout << i << ": " << inventory[i]->name << endl;
	}

	int pos;
	// Ask the user to input the position of the item they wish to examine
	cout << "Please enter the position of the object you wish to view: ";
	cin >> pos;

	// Output the details for that item to the screen
	cout << endl << endl << inventory[pos]->name << " " << inventory[pos]->value;

	// Create a new player
	player* player1 = new player();
	// Get the player to pick up the item we examined in the rooms inventory
	player1->pickup(inventory[pos]);
	// As the player now has the item remove it from the Room inventory
	inventory.erase(inventory.begin()+ pos);

	// Pause for key press
	getch();
	// Exit
	return 0;
}