使用迭代器和模板可以实现程序的通用性,容器和迭代器的设计成功的将算法和数据结构进行分离。
下面是使用迭代器实现的快速排序的核心代码。
template <class ForwardIt> void quicksort(ForwardIt first, ForwardIt last) { if (first == last) return; auto pivot = *std::next(first, std::distance(first, last) / 2); ForwardIt middle1 = std::partition(first, last, [pivot](const auto& em) { return em < pivot; }); ForwardIt middle2 = std::partition(middle1, last, [pivot](const auto& em) { return !(pivot < em); }); cout << "data is: " << endl; for_each(first, middle1, [](auto n) {cout << n << " "; }); cout << endl; for_each(middle2, last, [](auto n) {cout << n << " "; }); cout << endl; quicksort(first, middle1); quicksort(middle2, last); return; }