C ++设置搜索对元素? [英] C++ set search for pair element?

查看:131
本文介绍了C ++设置搜索对元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一组对< string,string>



c $ c> find()搜索一个字符串,它将在第一的对,然后如果我找到该字符串在第一我想从该函数返回第二。 / p>

我当前的尝试是..

  myList :: iterator i; 

i = theList.find(make_pair(realName,*));

return i-> second;是否可以接受C ++ 11?



  auto it = find_if(theList.begin(),theList.end(),
[& ,string>& val) - > bool {
return val.first == realName;
});

return it-> second;

或者在C ++ 03中,首先定义一个函子:

  struct MatchFirst 
{
MatchFirst(const string& realName):realName(realName){}

bool operator ()(const pair< string,string>& val){
return val.first == realName;
}

const string&真正的名字;
}

然后这样调用:

  myList :: iterator it = find_if(a.begin(),a.end(),MatchFirst(realName)); 
return it-> second;

这只会返回第一个匹配,但是从你的问题,看起来这就是你期望。


So I have a set of pairs<string ,string>

And I want to use find() to search for a single string which would be in the "first" of the pair, then if I find that string in first I want to return second from that function.

My current attempt is..

myList::iterator i;

i = theList.find(make_pair(realName, "*"));

return i->second;

解决方案

Is C++11 acceptable?

auto it = find_if(theList.begin(), theList.end(),
    [&](const pair<string, string>& val) -> bool {
        return val.first == realName;
    });

return it->second;

Or in C++03, first define a functor:

struct MatchFirst
{
        MatchFirst(const string& realName) : realName(realName) {}

        bool operator()(const pair<string, string>& val) {
                return val.first == realName;
        }

        const string& realName;
};

then call it like so:

myList::iterator it = find_if(a.begin(), a.end(), MatchFirst(realName));
return it->second;

This will only return the first match, but from your question, it looks like that's all you're expecting.

这篇关于C ++设置搜索对元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆