C++如何使用STL中的map find()函数?示例

2021年3月25日11:27:58 发表评论 884 次浏览

map::find()是C++ STL中的内置函数,它返回一个迭代器或常量迭代器,指向键在map中出现的位置。如果map容器中没有该键,则返回指向map.end()的迭代器或常量迭代器。

语法如下:

iterator=map_name.find(key)
        or 
constant iterator=map_name.find(key)

参数:该函数接受一个强制性参数键它指定要在地图容器中搜索的键。

返回值:该函数返回一个迭代器或常量迭代器, 该迭代器或常量迭代器引用键在映射中的位置。如果键不存在于地图容器中, 则它返回一个迭代器或一个常量迭代器, 该迭代器或常量引用map.end()。

搜索元素的时间复杂度:

在中搜索元素的时间复杂度

在std::map中搜索元素的时间复杂度是O(log n)。即使在最坏的情况下,它也将是O(log n),因为元素在内部存储为平衡二叉搜索树(BST),而在std::unordered_map中,搜索的最佳时间复杂度是O(1)。

下面是上述函数的使用说明:

CPP

// C++ program for illustration
// of map::find() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
     // Initialize container
     map< int , int > mp;
 
     // Insert elements in random order
     mp.insert({ 2, 30 });
     mp.insert({ 1, 40 });
     mp.insert({ 3, 20 });
     mp.insert({ 4, 50 });
 
     cout << "Elements from position of 3 in the map are : \n" ;
     cout << "KEY\tELEMENT\n" ;
 
     // find() function finds the position
     // at which 3 is present
     for ( auto itr = mp.find(3); itr != mp.end(); itr++) {
       
         cout << itr->first << '\t' << itr->second << '\n' ;
     }
 
     return 0;
}

输出如下

The elements from position 3 in map are : 
KEY    ELEMENT
3    20
4    50

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C++ STL通过激烈的问题解决过程来训练和掌握这些概念。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: