Lower_bound 匹配错误的字符串

Lower_bound matching wrong strings

现在我完全糊涂了。我整天都在谷歌搜索,但仍然不明白为什么这段代码不起作用。

我有 vectorstructs,那些 structsstring 属性。当我想在 vector 中添加一个新的 struct 时,首先我必须检查具有相同 string 属性 的 struct 是否已经存在。如果是,则不会添加。

#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()。它 returns 一个指向匹配元素('lowest' 的迭代器)如果值在范围内找到,并且迭代器等于 last(通常是 end())没有匹配项:

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;
}