Lower_bound匹配错误的字符串

Lower_bound matching wrong strings

本文关键字:错误 字符串 bound Lower      更新时间:2023-10-16

现在我完全困惑了。我整天都在谷歌上搜索,仍然不明白为什么这个代码不起作用。

我有structsvector,而那些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()的变体。如果在范围内找到值,它会向匹配元素("最低"元素)返回迭代器,如果没有匹配,则返回等于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;
}