从同一索引的两个不同阵列获取数据

时间:2012-07-07 03:13:02

标签: c++

我创建了一个这样的数组:

string mobs [5] = {"Skeleton", "Dragon", "Imp", "Demon", "Vampire"};
int mobHP[5] = {10, 11, 12, 13, 14, 15};

我创建了一个随机数生成器来获取我想要的暴徒号,但是我失败了。假设,生成的数字为4,我将如何将其等于或等于字符串第5号,以及第5个字符?

2 个答案:

答案 0 :(得分:3)

如果你有一个函数返回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);
}

答案 1 :(得分:0)

对于N元素数组,有效索引的范围为0N-1,其中0表示第一个元素,N-1表示最后一个元素。

由于您在此范围内生成了数字,因此它会直接映射到数组的元素。

如果你有值ix=4,它指的是第五个怪物。您可以访问mobs[ix]处的名称和mobHP[ix]处的运行状况。