Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Named Arrays

Tags:

c++

arrays

I would like to create arrays like this:

string users[1][3];

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

But I get this error:

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

Is it possible to create arrays like these in C++? In PHP, and Javascript they are very basic so I'm a bit surprised , how can I do it here?

like image 553
Adam Halasz Avatar asked Aug 30 '11 13:08

Adam Halasz


2 Answers

Array can only indexed by integers. If you want to index by chars, you need std::map or std::unordered_map in C++11. std::unordered_map is actually a hash table implementation. On the other hand std::map is red-black tree. So choose whatever fits your need.

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";
like image 120
Mu Qiao Avatar answered Oct 08 '22 10:10

Mu Qiao


The data structure you are looking for is sometimes called an "associative array". In C++ it is implemented as 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";

You don't need to specify the dimensions, as a map will grow whenever a new item is inserted.

like image 25
Robᵩ Avatar answered Oct 08 '22 11:10

Robᵩ