可以輸出例如陣列通過以下方式
std::cout << "Multidimensional Array:" << std::endl;
for (size_t i = 0; i < sizeof(shopInventory)/sizeof(*shopInventory); i++)
{
std::cout << shopInventory[i][0] << ": " << shopInventory[i][1] << std::endl;
}
或者你也可以做到這一點通過以下方式
std::cout << "Multidimensional Array:" << std::endl;
for (const auto &item : shopInventory)
{
std::cout << item[0] << ": " << item[1] << std::endl;
}
考慮到代替二維數組,您還可以聲明std::pair<std::string, std::string>
類型的對象的一維數組。例如
std::pair<std::string, std::string> shopInventory[] =
{
{ "Boots", "70" },
{ "Sword", "150" },
{ "Armor", "250" },
{ "Shield", "450" }
};
std::cout << "Multidimensional Array:" << std::endl;
for (size_t i = 0; i < sizeof(shopInventory)/sizeof(*shopInventory); i++)
{
std::cout << shopInventory[i].first << ": " << shopInventory[i].second << std::endl;
}
或
std::pair
你必須包含頭<utility>
要使用標準類。
對於你的任務,如果你要刪除的序列中的元素,最好是使用而非陣列
std::vector<std::array<std::string, 2>>
這裏至少有以下容器是一個示範項目
#include <iostream>
#include <vector>
#include <string>
#include <array>
int main()
{
std::vector<std::array<std::string, 2>> shopInventory =
{
{ "Boots", "70" },
{ "Sword", "150" },
{ "Armor", "250" },
{ "Shield", "450" }
};
for (const auto &item : shopInventory)
{
std::cout << item[0] << ": " << item[1] << std::endl;
}
return 0;
}
它的輸出是
Boots: 70
Sword: 150
Armor: 250
Shield: 450
根據您要執行的操作p與集合一起考慮使用例如關聯容器,如std::map
。
你想做什麼?爲什麼你使用一個空*指針*常量作爲索引?您是否嘗試打印'shopInventory [i] [j]'? –