Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...