问题
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