以下是如何使用std::partition()
作为Students
的vector
,对学生指针向量的修改很简单,但是可以用于更多的代码。 Live version。如果你与大量学生打交道,你可能想要做一些更有效的工作来检查A类的成员身份,例如使用set
或在排序的vector
上进行二分搜索。
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
struct Student {
uint32_t id;
string name;
};
bool operator==(const Student& a, const Student& b) {
return tie(a.id, a.name) == tie(b.id, b.name);
}
main() {
const auto jane = Student{3, "Jane"};
const auto zippy = Student{1, "Zippy"};
const auto classA = vector<Student>{jane, zippy};
auto allStudents = vector<Student>{{5, "Rod"}, jane, {4, "Freddy"}, zippy, {2, "Bungle"}};
partition(begin(allStudents), end(allStudents), [&](const auto& s){ return find(begin(classA), end(classA), s) == end(classA); });
for (const auto& s : allStudents) cout << s.id << ", " << s.name << "; ";
cout << endl;
}
输出是:
5, Rod; 2, Bungle; 4, Freddy; 1, Zippy; 3, Jane;
如果你真的想与vector<Student*>
s到工作由于某种原因,则主要的变化是在partition()
调用拉姆达切换find()
为find_if()
:
[&](const Student* s){ return find_if(begin(classA), end(classA),
[&](const Student* x){ return *x == *s; }) == end(classA); }
您需要为'std :: sort'的结构定义'operator <'来工作。 – CinCout
看看[std :: partition](http://en.cppreference.com/w/cpp/algorithm/partition)和[std :: stable_partition](http://en.cppreference.com/w/cpp /算法/ stable_partition)算法。 –
@GargAnkit不会工作,因为它是一个指针向量。他将不得不将自定义比较器传递给'std :: sort'。 –