2011-05-09 56 views
3

我想製作一個包含2個字符串列表(一個單數和一個複數)的數組數組。C++陣列,分別定義部分

string item_name[2][6]; 
string item_name[0] = {"bag of CinnaCandies", "can of Arizona Tea", "Starbucks Mocha Frappe", "copy of Section 8: Prejudice", "Sushi Box", "pair of Nike Jordans"}; 
string item_name[1] = {"bags of CinnaCandies", "cans of Arizona Tea", "Starbucks Mocha Frappes", "copies of Section 8: Prejudice", "Sushi Boxes", "pairs of Nike Jordans"}; 

我不知道正確的語法來做到這一點,我想保持它作爲2數組的數組,所以我可以有代碼,說:

if (quantity > 1) 
    { 
     cout << item_name[0][index]; 
    } 
    else 
    { 
     cout << item_name[1][index]; 
    } 

感謝。 :)

回答

2

正常,但的初始化,而不是常規的固定使用一個子陣列:

string item_name[2][6] = { 
    {"bag of CinnaCandies", "can of Arizona Tea", "Starbucks Mocha Frappe", "copy of Section 8: Prejudice", "Sushi Box", "pair of Nike Jordans"}, 
    {"bags of CinnaCandies", "cans of Arizona Tea", "Starbucks Mocha Frappes", "copies of Section 8: Prejudice", "Sushi Boxes", "pairs of Nike Jordans"} 
}; 
6

你在正確的軌道上。你只需要一個聲明,並嵌套括號,以便你有一個陣列數組:

string item_name[2][6] = {{"bag of CinnaCandies", "can of Arizona Tea", 
          "Starbucks Mocha Frappe", "copy of Section 8: Prejudice", 
          "Sushi Box", "pair of Nike Jordans"}, 
          {"bags of CinnaCandies", "cans of Arizona Tea", 
          "Starbucks Mocha Frappes", 
          "copies of Section 8: Prejudice", "Sushi Boxes", 
          "pairs of Nike Jordans"}}; 
2

上述兩個答案都是正確的。此外,你還可以用像這樣:

vector<string> item_name[2]; 

這樣,你仍然有「陣列」,但子數組大小不固定的數組,這樣你就可以繼續追加許多條目,你需要。

和當然,你也可以使用符號

item_name[0][index]; 

要在第一個頂級陣列獲得「指標」項目。

+0

謝謝。我看過載體,但不知道它們是什麼。我現在要去研究它們。 – vertevero 2011-05-13 15:50:32