菜鸟笔记
提升您的技术认知

c++ map.find使用方法

函数原型

iterator find (const key_type& k);
const_iterator find (const key_type& k) const;

返回值

An iterator to the element, if an element with specified key is found, or map::end otherwise.

If the map object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator.

Member types iterator and const_iterator are bidirectional iterator types pointing to elements (of type value_type).
Notice that value_type in map containers is an alias of pair<const key_type, mapped_type>.

例子

//map::find
#include <iostream>
#include <map>

int main ()
{
    std::map<char,int> mymap;
    std::map<char,int>::iterator it;

    mymap['a']=50;
    mymap['b']=100;
    mymap['c']=150;
    mymap['d']=200;

    it = mymap.find('b');
    if (it != mymap.end())
        mymap.erase (it);

    // print content:
    std::cout << "elements in mymap:" << '\n';
    std::cout << "a => " << mymap.find('a')->second << '\n';
    std::cout << "c => " << mymap.find('c')->second << '\n';
    std::cout << "d => " << mymap.find('d')->second << '\n';
    std::cout << "b => " << mymap.find('b')->second << '\n';
    std::cout << "e => " << mymap.find('e')->second << '\n';

    return 0;
}

执行结果

Output:

elements in mymap:
a => 50
c => 150
d => 200
b => 0
e => 0