Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ have a dictionary similar to Objective-C's NSDictionary?

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.

like image 209
unwise guy Avatar asked Nov 30 '22 02:11

unwise guy


2 Answers

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;
}
like image 75
Switch Avatar answered Dec 06 '22 21:12

Switch


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.

like image 43
Chris Innanen Avatar answered Dec 06 '22 20:12

Chris Innanen