// 包括序列容器 #include <vector> #include <deque> #include <list> #include <array> #include <forward_list> // 包括排序算法 #include <algorithm> class Base { public: // 将变量设置为v的值的构造方法 Base(int v): variable(v) { } int variable; }; int main() { // 创建2个要排序的元素 Base a(10); Base b(5); // 我们使用的是C ++ 11,因此让我们使用初始化列表插入项目。 std::vector <Base> vector = {a, b}; std::deque <Base> deque = {a, b}; std::list <Base> list = {a, b}; std::array <Base, 2> array = {a, b}; std::forward_list<Base> flist = {a, b}; // 我们可以使用内联lambda表达式对数据进行排序 std::sort(std::begin(vector), std::end(vector), [](const Base &a, const Base &b) { returna.variable< b.variable;}); // 我们还可以传递一个lambda对象作为比较器 // 并多次重复使用lambda auto compare = [](const Base &a, const Base &b) { returna.variable< b.variable;}; std::sort(std::begin(deque), std::end(deque), compare); std::sort(std::begin(array), std::end(array), compare); list.sort(compare); flist.sort(compare); return 0; }