使用另一个stl向量重新排序stl向量

时间:2015-08-14 04:37:48

标签: c++ vector stl

typedef struct tagSTUDENT
{
    UINT32 id;
    string name;

}STUDENT, *LP_STUDENT;

vector<LP_STUDENT> allStudents 
vector<LP_STUDENT> classA

我希望A班的学生在所有学生的开头或结尾。 allStudents未排序。 std :: sort也会根据id或其他标准对学生进行排序吗?

将classA插入allStudents&amp;消除重复是一个好方法吗?

1 个答案:

答案 0 :(得分:2)

以下是std::partition()vector Students的使用方法,对学生指针向量的修改很简单,但可以提供更多代码。 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*>,那么主要的变化是在find()调用lambda中切换find_if() partition()

[&](const Student* s){ return find_if(begin(classA), end(classA), 
                              [&](const Student* x){ return *x == *s; }) == end(classA); }