【问题标题】:Iterator and constant interator in C++C++中的迭代器和常量迭代器
【发布时间】:2009-12-23 17:39:33
【问题描述】:

有什么区别?

我希望能够查看一个元素是否在 HashMap 中,我刚刚发现如果我执行 h[element],如果未找到它将返回默认元素,而不是 null。如何使用迭代器查找方法来查看元素是否存在?

谢谢

【问题讨论】:

  • 这是两个不同的问题。

标签: c++ iterator


【解决方案1】:

假设您在谈论 STL 而不是某个 3rd 方库...m[key] 不仅会在 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
}

【讨论】:

  • 感谢您的更正,帕维尔。我没怎么用过地图:)
  • (我确实知道 -> 其次,我只是本能地没有输入它,因为没有经常使用它。但我没有理由忘记 ::iterator)
【解决方案2】:

您使用 find 方法查看 std::map 中是否有内容

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

【讨论】:

    【解决方案3】:

    主要区别在于const_iterator不能用于修改map中元素的值。

    使用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;
    

    【讨论】:

      【解决方案4】:

      正如其他答案所解释的,对于std::map,您可以使用find

      回答标题中的问题:

      对于迭代器,const 可以引用迭代器本身,或者指向迭代器指向的内容。这两个属性都是正交的。使用 STL 表示法,您有以下情况:

      • iterator 可以修改内容和迭代器。
      • const_iterator内容为const,可以修改迭代器
      • const iterator 内容可以修改,迭代器为const。
      • const const_iterator 内容和迭代器是不变的。

      指针也是类似的。在那里,const 也可以引用内容或指针本身。

      【讨论】:

        【解决方案5】:

        当您希望迭代器遍历 const 容器时,需要使用 const 迭代器。尝试将非 const 可修改迭代器分配给 const 容器将返回编译器错误。这是因为非常量迭代器可能会修改 const 容器。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-07
          • 1970-01-01
          • 1970-01-01
          • 2013-12-16
          相关资源
          最近更新 更多