gpt4 book ai didi

c++ - 为什么建议我在快速排序中使用指针?

转载 作者:行者123 更新时间:2023-11-28 05:05:14 27 4
gpt4 key购买 nike

我在 CPP 中编写了快速排序,它工作正常。但是当我检查谷歌编码标准时,它是这样建议的。我无法破译此消息,您能否解释一下我的代码有什么问题。

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;
}

最佳答案

Google 显然也有一种观点,认为非常量引用是不好的,因为它们在调用站点上使参数将被调用修改这一点变得不明显。

关于c++ - 为什么建议我在快速排序中使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997906/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com