您的位置:首页 > 编程语言 > C语言/C++

C#中Dictionary<TKey,TValue>和C++std::map<TK,TV>的对比

2014-08-19 16:13 316 查看
C#中使用Dictionary<TKey,TValue>,C++使用std::map<TK,TV>。map的内部实现是红黑树,Dictionary的实现是哈希表。DotNet中也有用树实现的字典类结构,叫SortedDictionary,似乎用得不多,效率也没有哈希表高,不过可以保持插入的数据是有序的。下面的对比是通过字符串来检索整数,为了写起来方便,C++中字符串直接用了LPCTSTR,并且typedefstd::map<LPCTSTR,int>
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐