2015-08-14 69 views
-1
typedef struct tagSTUDENT 
{ 
    UINT32 id; 
    string name; 

}STUDENT, *LP_STUDENT; 

vector<LP_STUDENT> allStudents 
vector<LP_STUDENT> classA 

我想让A班的学生在所有学生的开始或结束。 allStudents没有排序。 std :: sort也会根据id或其他标准对学生进行排序吗?使用另一个stl向量重新排序stl向量

在所有学生的末端插入classA &消除重复是一个好方法吗?

+2

您需要为'std :: sort'的结构定义'operator <'来工作。 – CinCout

+1

看看[std :: partition](http://en.cppreference.com/w/cpp/algorithm/partition)和[std :: stable_partition](http://en.cppreference.com/w/cpp /算法/ stable_partition)算法。 –

+2

@GargAnkit不会工作,因为它是一个指针向量。他将不得不将自定义比较器传递给'std :: sort'。 –

回答

2

以下是如何使用std::partition()作为Studentsvector,对学生指针向量的修改很简单,但是可以用于更多的代码。 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); } 
+0

我正在与大量的学生打交道。如果你可以编辑来提供一个有用的指针的答案。谢谢。 –

+0

@SunilMathew编辑描述如何使这个工作与'vector 's – mattnewport