0
我寫了CPP快速排序,它工作正常。但是當我檢查Google編碼標準時,建議您這樣做。我無法破譯這個信息,你能解釋我的代碼有什麼問題嗎?爲什麼我建議在快速排序中使用指針?
qs.cpp:8: Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A [runtime/references] [2]
qs.cpp:9: Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A [runtime/references] [2]
qs.cpp:25: Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A [runtime/references] [2]
qs.cpp:34: Is this a non-const reference? If so, make const or use a pointer: std::vector<int> &A [runtime/references] [2]
Done processing qs.cpp
Total errors found: 4
#include <iostream>
#include <vector>
#include <iomanip>
#include <utility>
void quickSort(std::vector<int> &A, int p, int r);
int partition(std::vector<int> &A, int p, int r);
int main() {
std::vector<int> a = {2, 8, 7, 1, 3, 5, 6, 4};
std::cout << std::setw(10) << "UnSorted Array:\n"
for (int ele : a) {
std::cout << ele << std::setw(5);
}
std::cout << std::endl << std::setw(10) << "Sorted Array:\n";
quickSort(a, 0, a.size()-1);
for (int ele : a) {
std::cout << ele << std::setw(5);
}
std::cout << std::endl;
}
void quickSort(std::vector<int> &A, int p, int r) {
int q;
if (p < r) {
q = partition(A, p, r);
quickSort(A, p, q-1);
quickSort(A, q+1, r);
}
}
int partition(std::vector<int> &A, int p, int r) {
int x = A[r];
int i = p-1;
for (int j = p; j < r; j++) {
if (A[j] <= x) {
i = i+1;
std::swap(A[i], A[j]);
}
}
std::swap(A[i+1], A[r]);
return i+1;
}
https://softwareengineering.stackexchange.com/questions/299021/non-optional-pointers-vs-non-const-references-in-c有答案。無論如何,Google風格的文檔不是標準文檔,從來沒有像許多cpp程序員不會因爲很多原因而堅持使用它。 –
我個人認爲非const引用沒有錯,它會美化代碼。 –
請不要使用Googles編碼標準作爲「良好實踐的權威來源」,它是Google編寫的,用於管理他們巨大的新代碼和舊代碼庫,並提供一致性,它們是(In * my * oppinion)* not *一個現代C++最佳實踐的好例子 –