我想创建这样的数组:
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中,它们是非常基础的,所以我有点惊讶,我怎么能在这里做到这一点呢?
发布于 2011-08-30 21:08:00
数组只能按整数编制索引。如果要按字符进行索引,则需要std::map或C++11中的std::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";发布于 2011-08-30 21:08:09
您正在寻找的数据结构有时被称为“关联数组”。在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都会增长。
发布于 2011-08-30 21:15:40
PHP和Javascript不是强类型的,在C++中,你可能希望创建一个结构来描述你的用户,而不是依赖于任意字符串作为键:
struct User {
size_t _age;
std::string _city;
std::string _country;
};然后,您确实可以创建一个索引来按名称引用这些用户(您可能还希望将所述名称存储在用户中)。这样做的两个容器通常是std::map和std::unordered_map。
std::map<std::string, User> users;
User& user = users["CIRK"];
user._age = 20;
user._country = "USA";
user._city = "New York";请注意,我通过创建引用在数组中缓存了查找(如果对象尚未存在,则会自动创建)。
https://stackoverflow.com/questions/7243589
复制相似问题