Lower_bound matching wrong strings

﹥>﹥吖頭↗ 提交于 2020-01-08 05:23:18

问题


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

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

回答1:


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


来源:https://stackoverflow.com/questions/36268977/lower-bound-matching-wrong-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!