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

时间:2017-07-09 15:13:47

标签: c++

我在CPP中写了快速排序,它工作正常。但是,当我使用Google Coding标准检查时,它会建议这一点。我无法破译此消息,请您解释我的代码有什么问题。

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

1 个答案:

答案 0 :(得分:1)

有一种观点,显然是由谷歌共享的,非常规引用是不好的,因为它们使得在调用网站上不明显的是该参数将被调用修改。