4

正如标题所说,有没有类似于 Objective-C 的NSDictionaryC++ 字典?我只需要一个包含(键,值)对并且可以添加和检索的数据结构。

4

4 回答 4

10

使用 std::map。

例如,从整数映射到 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;
}
于 2012-06-30T01:34:12.730 回答
5

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.

于 2014-04-10T17:41:50.930 回答
4

查看标准模板库中的 std::map 。它会做你需要的。

于 2012-06-30T01:27:14.900 回答
3

其他人已经回答了你的问题,我已经 +1 了。仍然觉得那里有更多可能有用的信息,我也去。

是的,C++ 有std::map. 然而,它是一个具有 O(log n) 搜索/插入复杂度的有序关联容器。通常,哈希表是首选。为此目的,有std::unordered_map与 O(1) 最佳情况查找。

通常,哈希表比排序树更受欢迎(尽管并非总是如此)。如果性能对您很重要,那么标准的 C++ 哈希表实现可能不适合您。毕竟,它非常通用。因此,您可能想看看Google Sparse Hash项目 - 它提供了密集哈希和稀疏哈希实现,可以提高您的性能并进行权衡(即速度与内存等),请参阅文档了解更多信息。

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!

于 2012-06-30T02:17:31.480 回答