我创建了一个这样的数组:
string mobs [5] = {"Skeleton", "Dragon", "Imp", "Demon", "Vampire"};
int mobHP[5] = {10, 11, 12, 13, 14, 15};
我创建了一个随机数生成器来获取我想要的暴民数,但我失败了。假设生成的数字是 4,我将如何将其等同于或等于字符串 mob number 5 和 mob hp number 5?
我创建了一个这样的数组:
string mobs [5] = {"Skeleton", "Dragon", "Imp", "Demon", "Vampire"};
int mobHP[5] = {10, 11, 12, 13, 14, 15};
我创建了一个随机数生成器来获取我想要的暴民数,但我失败了。假设生成的数字是 4,我将如何将其等同于或等于字符串 mob number 5 和 mob hp number 5?
如果您有一个返回 0 到 4 之间的随机数(数组索引)的函数,那么代码将类似于:
// Since we are using raw arrays we need to store the length
int array_length = 5
// Some function that returns a random number between
int randomIndex = myRandomNumberFunction(array_length)
// Now we select from the array using the index we calculated before
std::string selectedMobName = mobs[randomIndex]
int selectMobHP = mobHP[randomIndex]
然而,使用现代 C++ 实践实现这一目标的更好方法是创建一个怪物类并在向量中使用它,如下所示:
#include <vector>
#include <string>
#include <iostream>
// Normally we would use a class with accessors here but for the sake
// of brevity and simplicity we'll use a struct
struct Monster {
Monster(const std::string& in_name, const int in_health) :
name(in_name), health(in_health)
{}
std::string name;
int health;
};
// A vector is like an array that can grow larger if you add stuff to it
// Note: Normally we wouldn't use a raw pointer here but I've used it for
// for the sake of brevity. Instead we would either use a smart pointer
// or we would implement the Monster class with a 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 a random monster from the array
int random_index = myRandomNumberFunction(monsters.size());
Monster* selected_monster = monsters[random_index];
// Print the monster stats
std::cout << "You encounter " << selected_monster->name << " with "
<< selected_monster->health << "hp" << std::endl;
// Clean up the vector since we're using pointers
// If we were using smart pointers this would be unnecessary.
for(std::vector<Monster*>::iterator monster = monsters.begin();
monster != monsters.end();
++monster) {
delete (*monster);
}
对于元素数组,有效索引在toN
的范围内,其中表示第一个元素并表示最后一个元素。0
N-1
0
N-1
由于您在此范围内生成了一个数字,因此它直接映射到数组的元素上。
如果你有 value ix=4
,它指的是第五个怪物。您可以在 上访问名称mobs[ix]
和在 上的健康状况mobHP[ix]
。