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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With