Lower_bound匹配错误的字符串
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;
}
相关文章:
- 由cin中的字符串中未捕获空白引起的分割错误
- 将 GetLastError() 转换为带有错误字符串的异常
- Rapidjson 解析错误:字符串 (207) 中的编码无效
- 尝试对字符串[数组]>>cin 并出现错误(" "字符串下标超出范围")
- 如何检索 DirectX 9 的错误字符串
- 从 C++ => C 包装的 API(多线程)传输错误字符串
- 错误字符串下标超出c++范围
- 获取Openssl证书错误中的错误字符串
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 语法错误字符串方法C++
- 对于静态错误字符串,哪个的内存/性能效率更高,或者有替代方案
- 使用 strtok() 的错误字符串比较
- C++ 中的运行时错误字符串声明
- 我收到错误:字符串声明上的 C2501
- GCC:为什么一行代码中的错误(字符串和NULL的比较)会导致一长串错误消息
- 错误C2059:语法错误:'字符串'
- 致命错误:字符串:没有这样的文件或目录编译终止
- C++错误:字符串下标超出范围
- 这里面有什么错误?字符串赋值
- 是否有标准的方法来查询EGL错误字符串