C ++ Named Arrays

I would like to create such arrays:

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 such arrays in C ++? In PHP and Javascript they are very simple, so I'm a little surprised how can I do this here?

+7
source share
4 answers

An array can only be indexed with integers. If you want to index characters, you need std :: map or std :: unordered_map in C ++ 11 . std :: unordered_map is actually a hash table implementation. Std :: map, on the other hand, is a red-black tree. Therefore, choose everything that suits you.

 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"; 
+15
source

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 do not need to specify sizes, since map will increase whenever a new element is inserted.

+17
source

No, unfortunately, this is not possible with C ++. You should use display types like std::map or somthing, similar to what you are trying to execute.

You can try using something like this:

 #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"; 
+2
source

PHP and Javascript are not strongly typed, in C ++ you would like to create a structure that describes your user, and not rely on arbitrary strings as keys:

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

Then you can create an index to link to these users by name (you can also save the specified name with the user). The two containers for this are std::map and std::unordered_map , in the general case.

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

Note that I cached the search in the array by creating a link (and that the object is automatically created if it is not already present).

+2
source

All Articles