我正在尝试使用C ++容器和迭代器实现快速排序。
我是C ++ STL的新手。
我遇到了一个段错误。对于我所有的C程序,我总是使用valgrind来找出这样的情况,但现在它没有帮助。任何提示/建议/解决方案将不胜感激。
#include <iostream> #include <fstream> #include <vector> #include <iterator> #include <algorithm> using namespace std; void print(vector<int> A){ for(vector<int>::iterator i = A.begin(); i != A.end(); i++) cout << *i << " "; cout<<endl; } vector<int>::iterator Partition(vector<int>::iterator l, vector<int>::iterator r){ int x = *l; vector<int>::iterator i = l + 1; for(vector<int>::iterator j = l + 1; j <= r; j++){ if(*j < x){ iter_swap(j, i); i++; } } iter_swap(l, (i - 1)); return i - 1; } void QuickSort(vector<int>::iterator l, vector<int>::iterator r){ if (distance(l, r) <= 1) return; vector<int>::iterator p = Partition(l, r); QuickSort(l, p - 1); QuickSort(l + distance(l, p), r); } int main(int argc, const char * argv[]){ if (argc != 2){ cout << "Usage: ./Sort <file_name>" << endl; //<file_name> refers to a file of integers where each line contains a number return EXIT_FAILURE; } ifstream infile(argv[1]); vector<int> A; int num; while(infile >> num){ A.push_back(num); } //print(numbers); int n = 0; print(A); QuickSort(A.begin(), A.end()); print(A); //cout << n << endl; return EXIT_SUCCESS; }