如何使用算法过滤类向量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); });
}
您可以从boost使用filter_iterator
。下面是一个示例,其中底层集合是一个普通数组。
下面是未经测试的代码示例,供您使用;我必须对Student
(operator<<
对输出有效,通过std::string country() const
暴露的国家)做出某些假设
struct checkCountry
{
std::string country;
bool operator()(const Student& x)
{
return (x.country() == country);
}
};
int main()
{
std::vector<Student> studentList;
studentList.push_back(Student("Tom", 'M', "91213242", "America"));
studentList.push_back(Student("Jessilyn", 'F', "98422333", "Europe"));
typedef boost::filter_iterator<checkCountry, std::vector<Student>::iterator> FilterIter;
checkCountry predicate;
predicate.country = "America";
FilterIter filter_iter_first(predicate, studentList.begin(), studentList.end());
FilterIter filter_iter_last(predicate, studentList.end(), studentList.end());
std::copy(filter_iter_first, filter_iter_last, std::ostream_iterator<Student>(std::cout, " "));
}
我认为这就是您想要的:
struct country_filter
{
country_filter(const std::string& a_country): country(a_country) {}
void operator()(const Student& a_s) const
{
if (country == a_s.country)
{
std::cout << a_s.name << "n";
}
}
std::string country;
};
//
std::for_each(studentList.begin(), studentList.end(), country_filter("Ireland"));
C++11:
std::string country = "America";
std::for_each(studentList.begin(), studentList.end(), [&country] (const Student& a_s)
{
if (a_s.country == country)
{
std::cout << a_s.name << "n";
}
});
您可以使用实现()
运算符的类的对象。这被称为函子:
struct checkCountry {
const string& compare;
checkCountry(const string& compare) : compare(compare) {}
bool operator()(const string& x) { return x == compare; }
};
vector<Student> studentList;
studentList.push_back(Student("Tom", 'M', "91213242", "America"));
studentList.push_back(Student("Jessilyn", 'F', "98422333", "Europe"));
howMany = std::count_if(studentList.begin(), studentList.end(), checkCountry("America"));
您可以在任何需要一元谓词的算法中使用函子,例如std::count_if
、std::find_if
等。