Lower_bound匹配错误的字符串 [英] 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.
我有向量
structs
和那些 structs
有 string
属性。当我要添加一个新的 struct
到向量
,首先我要检查一个 struct
与 string
属性已经存在。如果是,则不会添加。
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;
}
推荐答案
尝试使用这个函数变化的标准 binary_search()
。如果在该范围中找到值,则返回一个迭代器到匹配的元素(最低的一个),并且迭代器等于 last
(通常 end()
):
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;
}
这篇关于Lower_bound匹配错误的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!