1

次のような配列を作成しました。

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

必要なモブ番号を取得するための乱数ジェネレーターを作成しましたが、失敗しました。生成された数が 4 であると仮定すると、それをどのように文字列モブ番号 5 とモブ HP 番号 5 と同一視または均等化しますか?

4

2 に答える 2

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);
}
于 2012-07-07T03:23:29.853 に答える
0

要素の配列のN場合、有効なインデックスは0~の範囲ですN-1。ここで、0は最初の要素をN-1示し、最後の要素を示します。

この範囲で生成された数値があるため、配列の要素に直接マップされます。

値が の場合ix=4、5 番目のモンスターを参照します。で名前にアクセスし、mobs[ix]でヘルスにアクセスしmobHP[ix]ます。

于 2012-07-07T16:49:24.733 に答える