c++ - Getting data from two different arrays for the same index -


i created array this:

string mobs [5] = {"skeleton", "dragon", "imp", "demon", "vampire"}; int mobhp[5] = {10, 11, 12, 13, 14, 15}; 

i created random number generator getting mob number want, failed. supposing, generated number 4, how equate or equalize string mob number 5, , mob hp number 5?

if have function returns random number between 0 , 4 (array indexes) code like:

// since using raw arrays need store length int array_length = 5 // function returns random number between int randomindex = myrandomnumberfunction(array_length) // select array using index calculated before std::string selectedmobname = mobs[randomindex] int selectmobhp = mobhp[randomindex] 

however better way achieve using modern c++ practices create monster class , use in vector so:

#include <vector> #include <string> #include <iostream> // use class accessors here sake // of brevity , simplicity we'll use struct struct monster { monster(const std::string& in_name, const int in_health) : name(in_name), health(in_health) {} std::string name; int health; }; // vector array can grow larger if add stuff // note: wouldn't use raw pointer here i've used // sake of brevity. instead either use smart pointer // or implement monster class copy or move constructor. std::vector<monster*> monsters; monsters.push_back(new monster("dragon", 5)); monsters.push_back(new monster("eelie", 3)); ... // arbitrary number of monsters monsters.push_back(new monster("slime", 1)); // select random monster array int random_index = myrandomnumberfunction(monsters.size()); monster* selected_monster = monsters[random_index]; // print monster stats std::cout << "you encounter " << selected_monster->name << " " << selected_monster->health << "hp" << std::endl; // clean vector since we're using pointers // if using smart pointers unnecessary. for(std::vector<monster*>::iterator monster = monsters.begin(); monster != monsters.end(); ++monster) { delete (*monster); } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -