C ++使用算法过滤类向量 [英] C++ To filter a class vector using algorithm

查看:146
本文介绍了C ++使用算法过滤类向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何筛选类向量,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));


解决方案

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

枚举区域{
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,\\\
),
is_american );

在C ++ 11中使用lambda,并允许选择区域:

  void show_students_from_region(const Region& region)
{
copy_if(students.begin(),students.end(),
ostream_iterator< Student>(cout,\\\
),
[&](const Student& student){return student.isFrom(region);}
}


How can I filter a class vector, studentList by its country from using algorithm? Meaning I only display the detail of students from country "America".

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);

Using a lambda in C++11, and allowing chosen regions:

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 ++使用算法过滤类向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆