我怎么能得到这个多维数组工作?
问题描述:
string shopInventory[4][2] = {
{"Boots", "70"},
{"Sword", "150"},
{"Armor", "250"},
{"Shield", "450"}
};
for (int i = 0; i < 4; i++) {
for(int j = 0; j < 2; j++) {
cout << "Multidimensional Array: " << shopInventory[i][NULL] << ": " << shopInventory[NULL][j] << endl;
}
}
我想做一个基本的商店系统,但我目前坚持如何输出与分离的细节数组。我怎么能得到这个多维数组工作?
预期输出:
靴子:70 剑:150 装甲:250 盾:450
实际输出:
多维数组:靴子:靴子 多维数组:靴子:70 多维阵列:剑:靴子 多维阵列:剑:70 多维阵列:护甲:靴子 M ultidimensional阵列:护甲:70 多维数组:护盾:靴子 多维数组:护盾:70
也就是有办法让我删除基于用户想要买什么数组中的元素?
答
你太过于复杂了。你的循环应该是这样的:
for (int i = 0; i < 4; i++) {
std::cout << "Multidimensional Array: " << shopInventory[i][0] << ": " << shopInventory[i][1] << std::endl;
}
,不要使用NULL
这样的 - 如果你想要把一个零的地方,使用0
答
可以输出例如阵列通过以下方式
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]'? –