copy

来源:互联网 发布:淘宝上的电器是正品吗 编辑:程序博客网 时间:2024/05/16 18:50

Examples. Still use student class.

#ifndef STUDENT_HPP_INCLUDED#define STUDENT_HPP_INCLUDEDusing namespace std;class student{private:    int NO;    int Grade;    string Name;public:    student():NO(0),Grade(0),Name(""){}    student(int NO_, int Grade_, string Name_):NO(NO_),Grade(Grade_),Name(Name_){}    student(const student& s){        this->setNO(s.getNO());        this->setGrade(s.getGrade());        this->setName(s.getName());    }    int getNO() const { return NO; }    int getGrade() const { return Grade; }    string getName() const { return Name; }    void setNO(int NO_) { NO = NO_; }    void setGrade(int Grade_) { Grade = Grade_; }    void setName(string Name_) { Name = Name_; }    bool operator==(student& s) const {        return this->getNO() == s.getNO();    }    bool operator<(student& s) const {        return this->getGrade() < this->getGrade();    }    void print(){        cout << NO << "\t" << Name << "\t" << Grade << endl;    }};#endif // STUDENT_HPP_INCLUDED


In main function ,

#include <vector>#include <functional>#include <iostream>#include <algorithm>#include <./student.hpp>using namespace std;int main(){    vector<student> sv;    student s1(1001, 70, "Sam");    student s2(1002, 85, "Tim");    student s3(1003, 90, "James");    student s4(1004, 50, "David");    sv.push_back(s1);    sv.push_back(s2);    sv.push_back(s3);    sv.push_back(s4);    cout << "Original Students Vector: " << endl;    auto itr = sv.begin();    while(itr!=sv.end()){        itr->print();        itr++;    }    // plain copy    vector<student> sv2;    copy(sv.begin(), sv.end(), back_inserter(sv2));    cout << "Backup Students Vector: " << endl;    itr = sv2.begin();    while(itr!=sv2.end()){        itr->print();        itr++;    }    // copy if student's grade is larger than 80    vector<student> sv3;    copy_if(sv.begin(), sv.end(), back_inserter(sv3), [](student s){return s.getGrade()>100;});    if(sv3.size()!=0){        cout << "Copy Students with Grade Larger Than 80: " << endl;        itr = sv3.begin();        while(itr!=sv3.end()){            itr->print();            itr++;        }    }else{        cout << "No such students!" << endl;    }    return 0;}
we first copy all the elements in sv, then we use copy_if .


0 0
原创粉丝点击