C#中Dictionary<TKey,TValue>和C++std::map<TK,TV>的对比
2014-08-19 16:13
387 查看
C#中使用Dictionary<TKey,TValue>,C++使用std::map<TK,TV>。map的内部实现是红黑树,Dictionary的实现是哈希表。DotNet中也有用树实现的字典类结构,叫SortedDictionary,似乎用得不多,效率也没有哈希表高,不过可以保持插入的数据是有序的。下面的对比是通过字符串来检索整数,为了写起来方便,C++中字符串直接用了LPCTSTR,并且typedefstd::map<LPCTSTR,int>
map_type;
map_type;
操作 | C++(STL) | C#(.net) | 说明 |
包含 | #include <map> | using System.Collections.Generic; | |
声明 | map_type map; map_type::iterator iter=map.begin(); | Dictionary<string, int> map = new Dictionary<string, int>(); | 如果是自定义的Key类型,C++中需要重载比较运算符;C#中可自定义相等比较器 |
插入 | map[_T("first")]=5; map.insert(map_type::value_type(_T("second"),2)); map.insert(map_type::value_type(_T("second"),3)); //不覆盖,不异常 | map.Add("first", 5); map["second"] = 2; //这种操作已经进行了插入 //map.Add("second", 3); //重复异常 | |
删除 | map.erase(iter); //iter有效且不等于map.end() map.erase(_T("first")); map.clear(); | map.Remove("first"); map.Clear(); | |
查询 | int val=map[_T("second")]; //没有则构造新的 iter=map.find(_T("first")); if (iter!=map.end()) val=iter->second; | int data = map["second"]; //不存在则异常 map.ContainsKey("third"); map.ContainsValue(5); map.TryGetValue("hello", out data); | 注意C++中下标检索时如果不存在这个元素也不产生错误 |
遍历 | for (iter=map.begin();iter!=map.end();++iter) { //遍历时删除 map.erase(iter++); } | foreach (KeyValuePair<string, int> pair in map) { //不能进行删除操作 } | |
大小 | map.size(); map.empty(); //是否为空 | map.Count; |
相关文章推荐
- 优化做缓存用的std::map<std::string, X> (自己的C++小工具系列1)
- C++ error: passing 'const std::map<>]' discards qualifiers或pass-by-reference-to-const-map导致的“discards qualifiers”
- C++中的&nbsp;pair&lt;map&lt;string,&nbsp;int&gt;::i…
- c++中bool数组与bitset,vector<bool>的使用与占用空间大小对比
- C /C++标准库 - <cstddef> (stddef.h)
- C++ 不能通过‘...’传递有不能平凡复制的类型‘const string {aka const class std::basic_string<char>}’
- include < bits / stdc++ .h>
- std::pair<MAP::iterator,bool>用法,可用来判断插入式否成功
- C++ 使用::std::vector<>
- C++ std::pair<>
- C++ 错误: ‘std::vector<float> feat’的声明隐藏了一个形参
- C++关于std namespace与# include<iostream>关系的有关问题
- C++ #include<string> 和 using std::string
- 实战c++中的string系列--std:vector<char> 和std:string相互转换(vector to stringstream)
- c++ error: reference to 'plus' is ambiguous ; template<class _Tp> struct std::plus
- error C2678 binary '<' : no operator found for map<std::string, shared_ptr<Foo>>
- C++用map记录字符串,怎么用map<string,int>才会不超时
- { 容器map }C++ <map>
- 实战c++中的vector系列--使用sort算法对vector进行排序(对vector<string>排序、使用稳定的排序std::stable_sort())
- C++中map<int,vector<int>>的初始化和访问方法