2011-08-30 36 views
7

我想這樣創建數組:C++命名的數組

string users[1][3]; 

users["CIRK"]["age"] = "20"; 
users["CIRK"]["country"] = "USA"; 
users["CIRK"]["city"] = "New York"; 

但我得到這個錯誤:

index.cpp: In function 'int main()': 
index.cpp:34: error: invalid types 'std::string [1][3][const char [5]]' for array subscript 
index.cpp:35: error: invalid types 'std::string [1][3][const char [5]]' for array subscript 
index.cpp:36: error: invalid types 'std::string [1][3][const char [5]]' for array subscript 

是否有可能在C++創建這樣的陣列?在PHP和Javascript中,它們非常基本,所以我感到有些驚訝,我該怎麼做呢?

回答

15

數組只能由整數索引。如果你想通過字符索引,你需要std :: mapstd :: unordered_map在C++ 11。 std :: unordered_map實際上是一個哈希表實現。另一方面,std :: map是紅黑樹。所以選擇適合你需要的東西。

std::unordered_map<std::string, std::unordered_map<std::string, std::string>> users; 

users["CIRK"]["age"] = "20"; 
users["CIRK"]["country"] = "USA"; 
users["CIRK"]["city"] = "New York"; 
17

您正在查找的數據結構有時稱爲「關聯數組」。在C++中,它被實現爲std::map

std::map<std::string, std::map<std::string, std::string> > users; 

users["CIRK"]["age"] = "20"; 
users["CIRK"]["country"] = "USA"; 
users["CIRK"]["city"] = "New York"; 

你並不需要指定維度,每當一個新的項目插入一個map將增長。

2

不,不幸的是,這對C++來說是不可能的。您必須使用像std::map或類似的映射類型來實現您正在嘗試的操作。

你可以嘗試使用財產以後這樣的:

#include <map> 
#include <string> 

... 
std::map<std::string, map<std::string, std::string> > mymap; 
users["CIRK"]["age"] = "20"; 
users["CIRK"]["country"] = "USA"; 
users["CIRK"]["city"] = "New York"; 
+0

請不要鼓勵使用'using namespace std;'。 http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c –

+0

好吧,我會改變我的答案。 – Constantinius

+3

使用名稱空間std沒有任何問題。事實上,命名空間是可管理的。有些地方你不應該使用它,例如頭文件被包含在多個地方,但在普通代碼中,它不僅可以接受,而且可以使用它。 – jcoder

2

PHP和JavaScript不是強類型的,在C++中,你將要創建的結構描述了你的用戶,而不是依靠任意字符串作爲鍵:

struct User { 
    size_t _age; 
    std::string _city; 
    std::string _country; 
}; 

然後,你確實可以創建一個索引來引用這些用戶的名字(你可能也想把這個名字存儲在用戶中)。一般來說,這兩個容器是std::mapstd::unordered_map

std::map<std::string, User> users; 
User& user = users["CIRK"]; 
user._age = 20; 
user._country = "USA"; 
user._city = "New York"; 

注意,我通過創建參考(以及如果不是已經存在的對象被自動創建的)高速緩存陣列中的查找。