C++ 中map 中迭代器的简单使用:

本文详细介绍了C++标准库中std::map::find函数的使用方法,包括其参数、返回值以及如何通过示例代码查找并删除指定键的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public member function
<map>

std::map::find

      iterator find (const key_type& k);
const_iterator find (const key_type& k) const;
Get iterator to element

Searches the container for an element with a key equivalent to k and returns an iterator to it if found, otherwise it returns an iterator to map::end.

Two keys are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).

Another member function, map::count, can be used to just check whether a particular key exists.

Parameters

k
Key to be searched for.
Member type  key_type is the type of the keys for the elements in the container, defined in  map as an alias of its first template parameter ( Key).

 

Return value

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>.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 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';

  return 0;
}



Output:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值