map按value查找相应元素

本文介绍了一种利用STL中的find_if算法在C++ map容器中搜索特定value的方法。通过自定义比较函数,实现对map中value进行匹配查找,并返回匹配元素的迭代器。示例代码展示了如何定义比较函数及进行查找的过程。

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

find_if算法用来在map中查找value符合条件的pair元素,返回指向该符合条件元素的迭代器,如果找到,那么返回最后一个元素的后一个元素end();

1.首先要定义头文件
 #include <algorithm>

2.定义一个比较函数

class map_finder
{
public:
    map_finder(const std::wstring &cmp_wstring) :m_s_cmp_string(cmp_wstring){}
    bool operator ()(const std::map<int, std::wstring>::value_type &pair)
    {
            return pair.second == m_s_cmp_string;
    }
private:
        const std::wstring &m_s_cmp_string;
};

3.查找

 map<int, wstring>::iterator it = m_listCtrl.m_secLineText.end();
       wstring s = str.GetString();
       it = std::find_if(m_listCtrl.m_secLineText.begin(), m_listCtrl.m_secLineText.end(), map_finder(s));
         if (it != m_listCtrl.m_secLineText.end())
        {
            int a = it->first;
            cout << " find!!!! " << endl;
        }
        else
        {
            cout << "Not find!!!! " << endl;
        }

转载于:https://www.cnblogs.com/ye-ming/p/7114794.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值