2009-12-23 40 views
0

有什麼區別?C++中的迭代器和常量interator

我想能夠看到一個元素是否在HashMap中,我只是發現如果我做h [element],它會返回默認元素,如果它沒有找到,而不是null。我將如何使用迭代器查找方法來查看元素是否在那裏?

感謝

+3

這是兩個不同的問題。 – 2009-12-23 17:41:47

回答

6

假設你正在談論STL而不是一些第三方庫... m[key]不只是返回默認的對象,如果關鍵是沒有在地圖上。它將創建一個新的元素在地圖中用那個鍵和一個默認構造的對象作爲值。

您可以使用此:

map<string, int> mymap; 
//add items to it 
map<string, int>::iterator it = mymap.find("key"); 
if (it != myMap.end()) { 
    // 'key' exists; (it->second) is the corresponding int 
} 

或者,如果您不需要獲取對象(你只是想知道,如果它存在):

map<string, int> mymap; 
//add items to it 
if (mymap.count("key") == 1) { 
    // 'key' exists 
} 
+0

感謝您的糾正,Pavel。我沒有使用過多的地圖:) – 2009-12-23 20:28:21

+0

(我知道 - >第二,我沒有本能地輸入它,因爲沒有用太多的東西,儘管我忘記了:: iterator) – 2009-12-23 20:34:33

2

您使用查找方法來查看,如果事情是在一個std ::地圖

std::map<std::string, std::string> myMap 
std::map<std::string, std::string>::iterator it = myMap.find("foo"); 
if(it != myMap.end()) { 
    //foo is in the map 
} else { 
    // foo isn't in the map 
} 

一個const_iterator是一個迭代器,當解引用回報const版本無論它指向至。在上面的例子中,如果itconst_iterator然後解除引用它會產生一個const std::string

1

的主要區別在於,const_iterator不能被用來修改在圖中的元素的值。

使用find方法

hash_map <int, int> hm1; 
    hash_map <int, int> :: const_iterator hm1_RcIter = hm1.find(2); 

    if (hm1_RcIter == hm1.end()) 
     cout << "The hash_map hm1 doesn't have an element " 
      << "with a key of 2." << endl; 
    else 
     cout << "The element of hash_map hm1 with a key of 4 is: " 
      << hm1_RcIter -> second << "." << endl; 
1

至於其他的答案解釋,對於std::map,您可以使用find

要回答這個問題在標題:

對於迭代器,const可以參考迭代器本身,還是到內容,迭代點。兩個屬性都是正交的。使用STL表示法,您有以下情況:

  • iterator可以修改內容和迭代器。
  • const_iterator內容是常量,迭代器可以被修改
  • const iterator內容可以被修改,迭代器是常量。
  • const const_iterator內容和迭代器是不變的。

指針類似。在那裏,const也可以引用內容或指針本身。

0

當你需要一個迭代器遍歷一個const容器時,需要const迭代器。試圖將一個非const可修改的迭代器賦值給一個const容器將返回一個編譯器錯誤。這是因爲非const迭代器可能會修改const容器。