C++ 使用自定义运算符使用std::pair进行二进制搜索
我尝试进行二进制搜索,包括整数对向量和整数,如下所示:C++ 使用自定义运算符使用std::pair进行二进制搜索,c++,binary-search,std-pair,C++,Binary Search,Std Pair,我尝试进行二进制搜索,包括整数对向量和整数,如下所示: #include <vector> #include <algorithm> using namespace std; typedef vector<pair<size_t,size_t> > int_pairs; bool operator<(const size_t& l, const pair<size_t,size_t>& r) {retu
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<pair<size_t,size_t> > int_pairs;
bool operator<(const size_t& l, const pair<size_t,size_t>& r)
{return r.first < l;} // useful for binary search
int main(){
int_pairs pairs_vec;
pairs_vec.push_back(pair <size_t,size_t>(1,2));
pairs_vec.push_back(pair <size_t,size_t>(2,2));
size_t i(2);
binary_search(pairs_vec.begin(),pairs_vec.end(),i);
}
#包括
#包括
使用名称空间std;
typedef向量int_对;
bool操作符这不起作用的原因是操作符可能更好地使用一些映射容器(例如std::map)?似乎std::binary\u search
坚持第三个参数与迭代器元素的类型相同,或者通过一些自定义强制转换操作符转换为它。因为没有< <代码> > SIEZHET和配对> /Cuffe这样的操作符,并且不能定义它,因为C++不允许“自由站立”转换运算符,所以您需要从<代码> i>代码>和(例如,0)构造一对,并将其作为第三个参数传递给std::binary_search
@dasblinkenlight我认为情况并非如此。对于没有运算符的自定义类型,如果我从I构造一对,代码将编译并工作。但我最好先从pairs_vec.中创建一个整数向量,这是我想要避免的。
erreur: no match for ‘operator<’ (operand types are ‘const long unsigned int’ and ‘std::pair<long unsigned int, long unsigned int>’)
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<size_t, size_t> my_pair;
typedef vector<pair<size_t,size_t> > int_pairs;
struct Comp {
// important: we need two overloads, because the comparison
// needs to be done both ways to check for equality
bool operator()(my_pair p, size_t s) const
{ return p.first < s; }
bool operator()(size_t s, my_pair p) const
{ return s < p.first; }
};
int main(){
int_pairs pairs_vec;
pairs_vec.push_back(pair <size_t,size_t>(1,2));
pairs_vec.push_back(pair <size_t,size_t>(2,2));
size_t i(2);
binary_search(pairs_vec.begin(),pairs_vec.end(),i, Comp());
}
bool operator<(const size_t& l, const pair<size_t,size_t>& r)
{
return r.first < l; // Wrong!
}
(!(a < b) && (!b < a))