本博文主要讲解equal 和 mismatch的使用方法
- 实例1
/*
*【1】equal 判断两个数组是否是相等的
*【2】mismatch 找到两个数组第一队不相等的数
*/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int a[] = {3,2,4,5,6,1};
int b[] = {3,2,4,5,1,6};
int len1 = sizeof(a)/sizeof(int);
int len2 = sizeof(b)/sizeof(int);
//equal
if(len1 == len2)
{
if(equal(a,a+len1,b))
cout<<"equal"<<endl;
else
cout<<"not equal"<<endl;
}
else
{
cout<<"not equal"<<endl;
}
mismatch
pair<int*,int*> p = mismatch(a,a+len1,b);
cout<<"第一对不相等的位置为:"<<p.first - a<<endl;
cout<<"值为:"<<*p.first<<" "<<*p.second<<endl;
system("pause");
return 0;
}
- 实例2
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class student
{
public:
int stdno;
string stdName;
int grade;
student(int stdno,string stdName,int grade)
{
this->stdno = stdno;
this->stdName = stdName;
this->grade = grade;
}
bool operator==(student s)
{
return this->grade == s.grade;
}
};
ostream& operator<<(ostream& os,student& s)
{
os<<"学号:"<<s.stdno<<"\t姓名:"<<s.stdName<<"\t分数:"<<s.grade<<endl;
return os;
}
int main()
{
vector<student>stdVec1;
vector<student>stdVec2;
student s1(1,"lijia",70);
student s2(2,"renyin",80);
student s3(3,"zhangchen",90);
student s4(4,"lijia",70);
student s5(5,"renyin",80);
student s6(6,"zhangchen",100);
stdVec1.push_back(s1);
stdVec1.push_back(s2);
stdVec1.push_back(s3);
stdVec2.push_back(s4);
stdVec2.push_back(s5);
stdVec2.push_back(s6);
typedef vector<student>::iterator it;
pair<it,it>result = mismatch(stdVec1.begin(),stdVec1.end(),stdVec2.begin());
cout<<"第一对不相等的学生信息如下:"<<endl;
student& std1 = *result.first;
student& std2 = *result.second;
//cout<<"学号:"<<std1.stdno<<"\t姓名:"<<std1.stdName<<"\t分数:"<<std1.grade<<endl;
//cout<<"学号:"<<std2.stdno<<"\t姓名:"<<std2.stdName<<"\t分数:"<<std2.grade<<endl;
cout<<std1<<endl;
cout<<std2<<endl;
system("pause");
return 0;
}