如何通过使用算法按国家过滤类 vector studentList?意思是我只显示来自“美国”国家/地区的学生的详细信息。

bool checkCountry (string x, string y)
{
  return (x == y);
}
vector<Student> studentList;
studentList.push_back(Student("Tom", 'M', "91213242", "America"));
studentList.push_back(Student("Jessilyn", 'F', "98422333", "Europe"));

最佳答案

using std::copy_if;
using std::ostream_iterator;
using std::cout;

enum Region {
    AMERICA,
    EUROPE,
    REST_OF_WORLD
};

bool is_american(const Student& student)
{
    return student.isFrom(AMERICA);
}

copy_if(students.begin(), students.end(),
        ostream_iterator<Student>(cout, "\n"),
        is_american);

在C++ 11中使用lambda,并允许选择区域:
void show_students_from_region(const Region& region)
{
    copy_if(students.begin(), students.end(),
            ostream_iterator<Student>(cout, "\n"),
            [&](const Student& student) { return student.isFrom(region); });
}

关于c++ - C++使用算法过滤类 vector ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8897208/

10-11 21:59
查看更多