开发者

How to use string indexes in c++ arrays (like php)?

开发者 https://www.devze.com 2022-12-08 10:00 出处:网络
How can I use a s开发者_如何转开发tring index in a c++ array (like in php)?You could use std::map to get an associative container in which you can lookup values by a string index. A map like std::map&

How can I use a s开发者_如何转开发tring index in a c++ array (like in php)?


You could use std::map to get an associative container in which you can lookup values by a string index. A map like std::map<std::string, int> would associate integer values with std::string lookup keys.


They're called associative arrays (or dictionaries) and the allow you to use any type you want as a key, instead of just integers. They're natively supported in PHP, in C++ you should probably use std::map unless you're in .net, which has its own dictionary class


The closest thing is probably a std::map.

Check out the wikipedia page for details.


Many have said that std::map is a choice. To be as effective as array index using, I think std::unordered_map may be better.

Because performance of std::map with key_type is a string possibly be very bad. Since comparing two strings will take O(string::size()) time in the worst case. So if the index strings are very long and similar and the number of them is too big, I would say that using std::map is unrealistic.

And I have some better way to implement it, but I'm not sure if they are feasible(especially the second one).

  1. Use a Trie.
  2. Use string_view instead of string.


You need to use something like std::map to have an object with behavior similar to associative array.


There is a data structure called Matrix library. This library supports 2D arrays and associative arrays that you are looking for.

Matrix<string> arr(3, 2);

// setting keys
arr[0][0] = "name";
arr[0][1] = "lastname";

// using array
arr[1]["name"] = "John";
arr[1]["lastname"] = "Parkers";

arr[2]["name"] = "Sam";
arr[2]["lastname"] = "Bendrou";

Here you can find documentation of Matrix library.


This functionality called Map in general. If you already use Boost you can use their Maps, if not you must think twice :) Ok, if not Dimtry right - std::map is what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号