Reputation: 1128
As the title says, is there a dictionary similar to Objective-C's NSDictionary
for C++? I just need a data structure that holds a (key,value) pair and can be added and retrieved.
Upvotes: 5
Views: 4430
Reputation: 99
You can use std::map or std::unordered_map (NSDictionary is unordered) in C++, however there is one major difference. Because the standard template libraries use templates for the value types, your map will be locked into one type each for both the key and the value. With NSDictionary, since everything is based off of NSObject, you can mix and match types.
If your data is homogenous, then you are all set. If you need that mixed-type behavior, you will need to create a custom class that can contain or derive into all of the types you wish to use.
Upvotes: 6
Reputation:
Others have answered your question already and I have +1'd them. Still having a feeling that there is a little bit more information out there that might be useful, here I go, too.
Yes, C++ has std::map
. However, it is an ordered associative container with O(log n) search/insert complexity. Oftentimes, a hash table is preferred. For that purpose there is std::unordered_map with O(1) best case lookup.
Oftentimes, hash tables are preferred over the sorted trees (though not always). If performance matters to you, a standard C++ hash table implementation might not fit you well. After all, it is extremely generic. So you might want to take a look at Google Sparse Hash project - it provides a dense hash and a sparse hash implementations that boost your performance and have theirs tradeoffs (i.e. speed vs memory etc), see documentation for more.
I am not sure how serious you are about learning C++, but in case you do want to learn it a bit more, you will be surprised with its rich set of other different containers and algorithms. I've once found SGI's STL documentation and have been using it for more than decade now, so I recommend it to you as well - http://www.sgi.com/tech/stl/table_of_contents.html. It could be just a little bit outdated, though, but is very useful. That is what C++ comes with out of the box. On top it, check out Boost, a set of different libraries that are not part of the standard library - http://www.boost.org/doc/libs/release/
Hope it helps!
Upvotes: 3
Reputation: 5366
Use std::map.
For example, to map from integers to std::string:
#include <map>
#include <string>
#include <iostream>
int main() {
std::map<int, std::string> my_map;
my_map[3] = "hello";
my_map[4] = "world";
std::cout << my_map[3] << " " << my_map[4] << std::endl;
return 0;
}
Upvotes: 10
Reputation: 4490
Check out std::map in the standard template library. It will do what you need.
Upvotes: 4