home *** CD-ROM | disk | FTP | other *** search
/ Beginning C++ Through Gam…rogramming (2nd Edition) / BCGP2E.ISO / source / chapter04 / heros_inventory3.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2004-04-11  |  1.5 KB  |  51 lines

  1. // Hero's Inventory 3.0
  2. // Demonstrates iterators
  3.  
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. int main()
  11. {
  12.     vector<string> inventory;
  13.     inventory.push_back("sword");
  14.     inventory.push_back("armor");
  15.     inventory.push_back("shield");
  16.  
  17.     vector<string>::iterator myIterator;
  18.     vector<string>::const_iterator iter;
  19.  
  20.     cout << "Your items:\n";
  21.     for (iter = inventory.begin(); iter != inventory.end(); ++iter)
  22.         cout << *iter << endl;
  23.  
  24.     cout << "\nYou trade your sword for a battle axe.";
  25.     myIterator = inventory.begin();
  26.     *myIterator = "battle axe";
  27.     cout << "\nYour items:\n";
  28.     for (iter = inventory.begin(); iter != inventory.end(); ++iter)
  29.         cout << *iter << endl;
  30.  
  31.     cout << "\nThe item name '" << *myIterator << "' has ";
  32.     cout << (*myIterator).size() << " letters in it.\n";
  33.  
  34.     cout << "\nThe item name '" << *myIterator << "' has ";
  35.     cout << myIterator->size() << " letters in it.\n";
  36.  
  37.     cout << "\nYou recover a crossbow from a slain enemy.";
  38.     inventory.insert(inventory.begin(), "crossbow");
  39.     cout << "\nYour items:\n";
  40.     for (iter = inventory.begin(); iter != inventory.end(); ++iter)
  41.         cout << *iter << endl;
  42.  
  43.     cout << "\nYour armor is destroyed in a fierce battle.";
  44.     inventory.erase((inventory.begin() + 2));
  45.     cout << "\nYour items:\n";
  46.     for (iter = inventory.begin(); iter != inventory.end(); ++iter)
  47.         cout << *iter << endl;
  48.  
  49.  return 0;
  50. }
  51.