Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c++ - Lower_bound matching wrong strings

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...