在C++ STL中"x和y"相等可以解释为以下两种情况:
1.一般我们认为“x和y相等” 等价于 “x==y”为真。
例如:在未排序的空间上进行的算法,如顺序查找find
#include <vector>
#include <algorithm>#include <iostream>
using namespace std;
int main()
{
vector<int> vec_test;
vector<int>::iterator ite_p;//定义迭代器
vec_test.push_back(4);
vec_test.push_back(8);
vec_test.push_back(2);
vec_test.push_back(1);// vec_test 有4、8、2、1四个元素。
ite_p=find(vec_test.begin(),vec_test.end(),4);//查找有没4,其是顺序查找的
if(ite_p!=vec_test.end())
{
cout<<*ite_p<<endl;
}
ite_p=find(vec_test.begin(),vec_test.end(),9);//查找有没9
if (ite_p==vec_test.end())
{
cout<<"not find"<<endl;
}
system("pause");
return 0;
}
测试结果
从测试结果可以看出这里相等即为:“x==y”为真。
2.“x和y相等”等价于“x小于y和y小于x同时为假”
例如:有序区间算法,如binary_search()等
//测试类
class Test
{
int flag;
public:
Test(int flag);
~Test(void);
bool operator<(const Test &test) const;
bool operator==(const Test &test) const;
};
Test::Test(int flag)
{
this->flag=flag;
}
{
this->flag=flag;
}
Test::~Test(void)
{
}
bool Test::operator<(const Test &test) const
{
cout<<this->flag<<"<"<<test.flag<<endl;
return false;//始终返回假
}
bool Test::operator==(const Test &test) const
{
return this->flag==test.flag;
}
//主函数
int main()
{
Test test_array[]={Test(1),Test(2),Test(3),Test(4),Test(5)};
cout<<binary_search(test_array,test_array+4,Test(55))<<endl;//找到输出1否则输出0
system("pause");
return 0;
}
测试结果
从结果可以找到55,其查找过程始终未调用重载成员函数bool Test::operator==(const Test &test) const而是调用重载成员函数bool Test::operator<(const Test &test) const;
其判断“x和y相等”方法是“x小于y和y小于x同时为假”的时候,由于该成员函数我们的返回值始终为假,这样会在最后使得“x小于y和y小于x同时为假”成立,因此,无论我们给什么值去查找返回值一定1(即一定能找到)。