[英]Lower_bound matching wrong strings
現在我完全糊塗了。 我整天在谷歌上搜索,但仍然不明白為什么這段代碼不起作用。
我有structs
vector
,這些structs
具有string
屬性。 當我想在vector
添加一個新struct
,首先我必須檢查是否已經存在具有相同string
屬性的struct
。 如果是,則不會添加。
#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()
)的迭代器:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.