C++设置对配对元素的搜索?
因此,我有一组pairs< string,string>
,并且我想使用find()
搜索一个字符串,该字符串将在该字符串中配对,然后,如果我第一次找到该字符串,我想从该功能返回第二个字符串。
我目前的尝试是..
myList::iterator i;
i = theList.find(make_pair(realName, "*"));
return i->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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C ++ 11可以接受吗?
或在C ++ 03中,首先定义一个函数:
然后将其称为So:
这只会返回第一场比赛,但是从您的问题来看,看起来这就是您所期望的。
Is C++11 acceptable?
Or in C++03, first define a functor:
then call it like so:
This will only return the first match, but from your question, it looks like that's all you're expecting.
您可以使用
std :: set&lt; std :: pair&lt; std :: string,std :: string&gt; &gt;
为此,您将需要自定义对此进行比较对象,因为这对夫妇的关系操作员为此采取了这两个元素。也就是说,似乎您实际上应该使用
std :: map&lt; std :: String,std :: string&gt;
而不是。You can use
std::set<std::pair<std::string, std::string> >
for this but you will need a customcomparison object for this because the pair's relational operator takes both elements for this. That said, it seems as if you actually should use a
std::map<std::string, std::string>
instead.&lt;
的定义std :: Pair
实现词典订单和“”
是字符串的最小元素。结合在一起:诀窍是适当地使用
lower_bound
。end()
,则找不到任何有趣的东西。it-&gt; first&gt; = key
,因此我们摆脱了&gt;
案例(我们对我们不感兴趣),我会指出,尽管这只是返回该范围的第一个元素。如果您对所有元素感兴趣,请尝试:
这将返回
s
的全部节点,其第一个元素等于key
。然后,您只需要在此范围内迭代:甚至不必担心
lower_bound
或upper_bound
的返回是否结束。lower_bound
返回end()
,那么上端> upper_bound
,并且如果lower_bound
指向一个it-&gt; first&gt;的节点键
,然后upper_bound
将指向相同的节点,而跳过了范围的循环:无需进行特殊检查,范围最终是空的。没有匹配,因此在它们上面的循环...一张支票跳过。
The definition of
<
forstd::pair
implements a lexicographical order and""
is the minimum element for strings. Combining this we get:The trick is using
lower_bound
appropriately.end()
, then it did not find anything interesting.it->first >= key
so we get rid of the>
case (of no interest to us)I would point out though that this only returns the first element of the range. If you are interested in all elements, try:
This will return the full range of nodes in
s
whose first element is equal tokey
. You then just have to iterate over this range:And you don't even have to worry whether the return of
lower_bound
orupper_bound
was end or not.lower_bound
returnsend()
, then so doesupper_bound
, and the loop is skippedlower_bound
points to a node for whichit->first > key
, thenupper_bound
will point to that same node, and the loop is skippedThat is the power of ranges: no need to make special checks, the ranges just end up empty when there is no match, and so the loop over them... is skipped in a single check.