C#中对应C++ STL
DotNet下的泛型容器類封裝在System.Collections.Generic,使用的十分廣泛。C++則靠STL實現(xiàn)了泛型容器與算法。下面對二者做一個對比,只談用法,不深究原理。對比的內(nèi)容有數(shù)組、鏈表和字典三種結構。
一、數(shù)組
C#使用List<T>,C++用的是std::vector<T>,內(nèi)部實現(xiàn)都是數(shù)組,也就是一塊連續(xù)的內(nèi)存區(qū)域,插入、刪除操作慢,隨機訪問速度快。
操作 |
C++(STL) |
C#(.net) |
說明 |
包含 |
#include <vector> |
using System.Collections.Generic; |
C++中也可以using namespace std; |
聲明 |
std::vector<int> array; |
List<int> array = new List<int>(); |
以int型數(shù)據(jù)為例 |
迭代器聲明 |
std::vector<int>::iterator iter=array.begin(); |
List<int>.Enumerator iter = array.GetEnumerator(); |
C#中迭代器不常用 |
插入 |
array.push_back(4); |
array.Add(4); |
迭代器操作后失效 |
查詢 |
int val=array[0]; |
int val = array[0];
array.Contains(5); //是否包含5 |
|
刪除 |
array.pop_back(); //刪除最后的元素 |
array.Remove(1); //刪除"1”這個元素 |
迭代器操作后失效 |
大小 |
array.empty(); |
array.Count; //元素數(shù) |
|
遍歷 |
for (std::vector<int>::size_type i=0;i<array.size();++i){} |
for (int i = 0; i < array.Count; i++){} |
C++中第二種常用,C#中第三種常用(我是這么覺得……) |
排序 |
std::sort(array.begin(),array.end()); |
array.Sort(); |
C++中要#include <algorithm>,上面的for_each也是 |
二、鏈表
C#使用LinkedList<T>,C++用的是std::list<T>,內(nèi)部實現(xiàn)都是鏈表,插入、刪除速度快,隨機訪問速度慢。鏈表的操作與數(shù)組十分相似,不同的地方大致有:
1. 任何通過下標訪問的方式都是無效的,查看容量也是無效的,這是由鏈表的性質決定的。對鏈表的查詢操作要通過迭代器進行。也就是說,上表中“查詢”、“遍歷”的第一種方法、“大小”中的容量都是非法操作。
2. 插入刪除的時候也不能指定下標,C++中除了push_back()外,多了一個push_front(),C#中不能使用Add()、Insert(),要使用AddBefore()/AddAfter()/AddFirst()/AddLast()。
3. 排序在C++中直接用list.sort()。
4. std::list<T>要加頭文件:#include <list>
三、字典
C#中使用Dictionary<TKey,TValue>,C++使用std::map<TK,TV>。map的內(nèi)部實現(xiàn)是紅黑樹,Dictionary的實現(xiàn)是哈希表。DotNet中也有用樹實現(xiàn)的字典類結構,叫SortedDictionary,似乎用得不多,效率也沒有哈希表高,不過可以保持插入的數(shù)據(jù)是有序的。下面的對比是通過字符串來檢索整數(shù),為了寫起來方便,C++中字符串直接用了LPCTSTR,并且typedef std::map<LPCTSTR,int> map_type;
操作 |
C++(STL) |
C#(.net) |
說明 |
包含 |
#include <map> |
using System.Collections.Generic; |
|
聲明 |
map_type map; |
Dictionary<string, int> map = new Dictionary<string, int>(); |
如果是自定義的Key類型,C++中需要重載比較運算符;C#中可自定義相等比較器 |
插入 |
map[_T("first")]=5; |
map.Add("first", 5); |
|
刪除 |
map.erase(iter); //iter有效且不等于map.end() |
map.Remove("first"); |
|
查詢 |
int val=map[_T("second")]; //沒有則構造新的 |
int data = map["second"]; //不存在則異常 |
注意C++中下標檢索時如果不存在這個元素也不產(chǎn)生錯誤 |
遍歷 |
for (iter=map.begin();iter!=map.end();++iter) |
foreach (KeyValuePair<string, int> pair in map) //不能進行刪除操作 } |
|
大小 |
map.size(); |
map.Count; |
|