3.4 使用數(shù)組
雖然string對(duì)象提供了非常不錯(cuò)的使用字符序列的方法,但是數(shù)組可以用于任意類(lèi)型的元素。也就是說(shuō),可以用數(shù)組存儲(chǔ)一個(gè)整型序列來(lái)表示一個(gè)高分列表,也能夠存儲(chǔ)程序員自定義類(lèi)型的元素,如RPG游戲中某個(gè)角色可能持有的物品構(gòu)成的序列。
3.4.1 Hero's Inventory程序簡(jiǎn)介
Hero's Inventory程序維護(hù)一個(gè)典型RPG游戲中主人公的物品欄。像大多數(shù)RPG游戲一樣,主人公來(lái)自一個(gè)不起眼的小村莊,他的父親被邪惡的軍閥殺害(如果他的父親不去世的話(huà)就沒(méi)有故事了)?,F(xiàn)在主人公已經(jīng)成年,是時(shí)候復(fù)仇了。
本程序中,主人公的物品欄用一個(gè)數(shù)組來(lái)表示。該數(shù)組是一個(gè)string對(duì)象的序列,每個(gè)string對(duì)象表示主人公擁有的一個(gè)物品。主人公可以交易物品,甚至發(fā)現(xiàn)新的物品。程序如圖3-4所示。
從Course Technology網(wǎng)站(www.courseptr.com/downloads)或本書(shū)合作網(wǎng)站(http://www. tupwk.com.cn/downpage)上可以下載到該程序的代碼。程序位于Chapter 3文件夾中,文件名為heros_inventory.cpp。
圖3-4 主人公的物品欄是存儲(chǔ)在數(shù)組中的string對(duì)象序列
// Hero's Inventory
// Demonstrates arrays
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int MAX_ITEMS = 10;
string inventory[MAX_ITEMS];
int numItems = 0;
inventory[numItems++] = "sword";
inventory[numItems++] = "armor";
inventory[numItems++] = "shield";
cout << "Your items:\n";
for (int i = 0; i < numItems; ++i)
{
cout << inventory[i] << endl;
}
cout << "\nYou trade your sword for a battle axe.";
inventory[0] = "battle axe";
cout << "\nYour items:\n";
for (int i = 0; i < numItems; ++i)
{
cout << inventory[i] << endl;
}
cout << "\nThe item name '" << inventory[0] << "' has ";
cout << inventory[0].size() << " letters in it.\n";
cout << "\nYou find a healing potion.";
if (numItems < MAX_ITEMS)
{
inventory[numItems++] = "healing potion";
}
else
{
cout << "You have too many items and can't carry another.";
}
cout << "\nYour items:\n";
for (int i = 0; i < numItems; ++i)
{
cout << inventory[i] << endl;
}
return 0;
}