Video Coming Soon...

Created by Zed A. Shaw Updated 2026-04-30 02:05:52

48: Iterators && More Containers

This exercise is pending. Quick notes about this exercise:

The Code

See how I did it.View Source file ex48.cpp Only

#include <fmt/core.h>
#include <string>
#include <random>
#include <memory>

std::random_device RNG;
std::mt19937 GENERATOR(RNG());

using std::shared_ptr, std::make_shared;

struct Combatant {
  std::string name;
  int damage{0};
  int hp{0};
  float hearing_distance{0.0f};
};

int random_number(int from, int to) {
  std::uniform_int_distribution rand(from, to);
  return rand(GENERATOR);
}

void fight(shared_ptr<Combatant> attacker, shared_ptr<Combatant> defender) {
  int damage = random_number(0, attacker->damage);

  if(damage > 0) {
    defender->hp -= damage;
    fmt::println("{} hit {} for {}. {} now has {} hp",
        attacker->name, defender->name, damage,
        defender->name, defender->hp);
  } else {
    fmt::println("{} missed {}!",
        attacker->name, defender->name);
  }

  if(defender->hp <= 0) {
    fmt::println("{} died. {} wins! {} has {} HP",
        defender->name, attacker->name,
        attacker->name, attacker->hp);
  }
}

std::vector<shared_ptr<Combatant>> fill_arena(int combatants) {
  std::vector<shared_ptr<Combatant>> arena;

  for(int i = 0; i < combatants; i++) {
    std::string name = fmt::format("Giant Rat #{}", i);
    int hp = random_number(5,20);
    int damage = random_number(2,10);
    arena.push_back(make_shared<Combatant>(name, damage, hp, 1.4f));
  }

  return arena;
}

int main(int argc, char* argv[]) {
  auto arena = fill_arena(4);
  auto player = make_shared<Combatant>("Player", 20, 50, 1.4f);
  bool player_turn = false;

  // now with multiple combatants we have to keep going until the player dies
  while(!arena.empty() && player->hp > 0) {
    // randomly select a combatant
    size_t enemy_at = size_t(random_number(0, arena.size() - 1));
    auto who = arena.at(enemy_at);
   
    if(player_turn) {
      fight(who, player);
    } else {
      fight(player, who);
    }

    // now how to remove when dead
    if(who->hp <= 0) {
      arena.erase(arena.begin() + enemy_at);
      fmt::println("-- 1 Down, {} To Go!", arena.size());
    }

    player_turn = !player_turn;
  }

  if(arena.empty()) {
    fmt::println("The Player Wins! You defeated all of the rats.");
  } else {
    fmt::println("You Died! The Rats Win.");
  }
}

The Breakdown

line of code
Description.

The Discussion

Blah blah.

Further Study

Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.