2009-12-23 38 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容器。