Lower_bound匹配错误的字符串 [英] Lower_bound matching wrong strings

查看:133
本文介绍了Lower_bound匹配错误的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我完全感到困惑。

Now I am completely confused. I am googling all day and still can't get why this code doesn't work.

我有向量 structs 和那些 structs string 属性。当我要添加一个新的 struct 向量,首先我要检查一个 struct string 属性已经存在。如果是,则不会添加。

I have vector of structs and those structs have string property. When I want to add a new struct into vector, as first I have to check whether a struct with the same string property is already there. If it is, it won't be added.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Try{
    string name;
    Try( string name) : name ( name ) { }
    bool                operator <                  ( const Try & a ) const
    {
        return name < a . name;
    }
};


int main(){

    vector<Try> vektor;
    Try *n;

    vektor . push_back( Try( "Prague" ) );

    n = new Try( "Brno" );


    vector<Try>::iterator it = lower_bound( vektor . begin(), vektor . end(), n -> name);

    if( it == vektor . end() ){
        cout << "not included" << endl;
        cout << it -> name << endl;
    }
    else
        cout << "included" << endl;

    return 0;
}


推荐答案

尝试使用这个函数变化的标准 binary_search()。如果在该范围中找到值,则返回一个迭代器到匹配的元素(最低的一个),并且迭代器等于 last (通常 end()):

Try using this function that's a variation of the standard binary_search(). It returns an iterator to the matching element (the 'lowest' one) if the value is found in the range, and an iterator equal to last (usually end()) when there's no match:

template< class ForwardIt, class T >
ForwardIt binary_search_ex(ForwardIt first, ForwardIt last, const T& value)
{
    ForwardIt it = std::lower_bound(first, last, value);

    if ((it != last) && (value < *it)) it = last;

    return it;
}

这篇关于Lower_bound匹配错误的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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