您可以通过以下方式输出数组,例如
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<std::string, std::string> shopInventory[] =
{
{ "Boots", "70" },
{ "Sword", "150" },
{ "Armor", "250" },
{ "Shield", "450" }
};
std::cout << "Multidimensional Array:" << std::endl;
for (const auto &item : shopInventory)
{
std::cout << item.first << ": " << item.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
根据您要对集合执行的操作,考虑使用例如std::map 等关联容器。