vector<class> 的查找

本文介绍了一个使用 C++ 实现的学生信息管理系统。该系统通过重载 student 类的等于运算符来实现学生信息的查找,并提供了按姓名和成绩排序的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做vector<class>的查找时查了一些方法。记录下操作符重载的一种方法

题目是要求记录学生的信息,然后能够按照姓名和成绩排序,还有一个查找成绩的功能
核心是
student类中重载操作符
bool operator ==(const student &stu)const{
    return stu.name==name;
}

然后find函数
vector<student>::iterator it;
   it=find(stu.begin(),stu.end(),s);


全部代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class student{
private:
    string name;
    int num;
public:
    student(){};
    
    void assign(string a,int n){
        name=a;num=n;
    }
    string showname(){return name;}
    int shownum(){return num;}
    //重载操作符==
    bool operator ==(const student &stu)const{
    return stu.name==name;
    }
};
vector<student>stu;

bool cmp1(student a,student b){
return a.showname()<b.showname();
}

bool cmp2(student a,student b){
return a.shownum()<b.shownum();
}

void print(){
    vector<student>::iterator it;
    for(it=stu.begin();it!=stu.end();it++){
        cout<<(*it).showname()<<" "<<(*it).shownum()<<endl;
    }
}
int main()
{
    student s;
    string a;int n;
    while((cin>>a)&&a!="00"){
        cin>>n;
        s.assign(a,n);
        stu.push_back(s);
    }
    //输入指令
    cout<<"输入指令,1是按照姓名排序,2是按照成绩排序,3是查询某人成绩"<<endl;
    int ins;
    cin>>ins;
    if(ins==1){
        sort(stu.begin(),stu.end(),cmp1);
        print();
    }
    else if(ins==2){
        sort(stu.begin(),stu.end(),cmp2);
        print();
    }
else if(ins==3){
    string req;
    cin>>req;
    s.assign(req,0);
        vector<student>::iterator it;

    it=find(stu.begin(),stu.end(),s);
        cout<<(*it).showname()<<" "<<(*it).shownum()<<endl;
}
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值