C++ map find()函数

C++ map find()函数

C++ map find() 函数用于 查找具有给定键值k的元素 。如果找到元素,则返回一个指向该元素的迭代器。否则,返回一个指向map结尾的迭代器,即map::end()。

语法

 iterator find (const key_type& k);             // until C++ 11
const_iterator find (const key_type& k) const;    //since C++ 11

参数

k :指定要在映射容器中搜索的键。

返回值

如果找到了元素,则返回一个迭代器,指向该元素。否则,返回指向映射末尾的迭代器,即map::end()。

示例1

让我们看一个简单的示例,查找给定键值的元素。

#include <iostream>
#include <map>
using namespace std;
int main(void) {
   map<char, int> m = {
            {'a', 100},
            {'b', 200},
            {'c', 300},
            {'d', 400},
            {'e', 500},
            };

   auto it = m.find('c');

   cout << "Iterator points to " << it->first << 
      " = " << it->second << endl;

   return 0;
}

输出:

Iterator points to c = 300

在上面的示例中,find()函数返回给定键值’c’的值。

示例2

让我们来看一个简单的查找元素的示例。

#include <iostream>
#include <map>
using namespace std;
int main(void) {
   map<char, int> m = {
            {'a', 100},
            {'b', 200},
            {'c', 300},
            {'d', 400},
            {'e', 500},
            };

    auto it = m.find('e');

    if ( it == m.end() ) {
    // not found
     cout<<"Element not found";
    } 
    else {
        // found
        cout << "Iterator points to " << it->first << " = " << it->second << endl;
    }

   return 0;
}

输出:

Iterator points to e = 500

在上面的示例中,find()函数在map m中查找键值e,如果在map中找不到,则返回一个未找到的消息,否则它将显示该map。

示例3

让我们看一个简单的示例。

#include <iostream>
#include <map>
 using namespace std;
int main()
{
    int n;
    map<int,char> example = {{1,'a'},{2,'b'},{3,'c'},{4,'d'},{5,'e'} };

    cout<<"Enter the element which you want to search: ";
    cin>>n;

    auto search = example.find(n);
    if (search != example.end()) {
        cout << n<<" found and the value is " << search->first << " = " << search->second << '\n';
    } else {
        cout << n<<" not found\n";
    }
}

输出:

Enter the element which you want to search: 4
4 found and the value is 4 = d

在上面的示例中,find()函数用于根据用户提供的键值找到元素。

示例4

让我们看一个简单的示例。

#include <iostream>
#include <map>

using namespace std;

int main ()
{
  map<char,int> mymap;
  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:
  cout << "elements in mymap:" << '\n';
  cout << "a => " << mymap.find('a')->second << '\n';
  cout << "c => " << mymap.find('c')->second << '\n';
  cout << "d => " << mymap.find('d')->second << '\n';

  return 0;
}

输出:

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程