C++命名数组

Ada*_*dam 8 c++ arrays

我想创建这样的数组:

string users[1][3];

users["CIRK"]["age"] = "20";
users["CIRK"]["country"] = "USA";
users["CIRK"]["city"] = "New York";
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

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
Run Code Online (Sandbox Code Playgroud)

是否可以在C++中创建这样的数组?在PHP和Javascript中它们非常基本所以我有点惊讶,我怎么能在这里做到这一点?

Rob*_*obᵩ 18

您正在寻找的数据结构有时称为"关联数组".在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";
Run Code Online (Sandbox Code Playgroud)

您无需指定尺寸,因为map每当插入新项目时它都会增长.


Mu *_*iao 17

数组只能用整数索引.如果要按字符索引,则需要在C++ 11中使用std :: mapstd :: unordered_map.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";
Run Code Online (Sandbox Code Playgroud)