【STL】非变异算法之比较

本博文主要讲解equal 和 mismatch的使用方法

  1. 实例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;
}
  1. 实例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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值