2017-10-19 115 views
-3
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

也就是有辦法讓我刪除基於用戶想要買什麼數組中的元素?

+1

你想做什麼?爲什麼你使用一個空*指針*常量作爲索引?您是否嘗試打印'shopInventory [i] [j]'? –

回答

1

你太過於複雜了。你的循環應該是這樣的:

for (int i = 0; i < 4; i++) { 
    std::cout << "Multidimensional Array: " << shopInventory[i][0] << ": " << shopInventory[i][1] << std::endl; 
} 

,不要使用NULL這樣的 - 如果你想要把一個零的地方,使用0

-1

可以輸出例如陣列通過以下方式

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

相關問題