簡體   English   中英

關於帶有std :: vector的quicksort的問題

[英]Question about quicksort with std::vector

以下是我從互聯網上發現的一些代碼,這些代碼使用整數數組作為輸入。 它工作正常,但是如果我將數組更改為vector,它只會打印原始輸入95、45、48、98、1、485、65、478、1、2325。誰能解釋它發生的原因以及如何解決它?

#include <iostream>
#include <vector>

using namespace std;



            void printArray(vector<int> array, int n)
            {
                for (int i = 0; i < n; ++i)
                    cout << array[i] << endl;
            }

            void quickSort(vector<int> array, int low, int high)
            {
                int i = low;
                int j = high;
                int pivot = array[(i + j) / 2];
                int temp;

                while (i <= j)
                {
                    while (array[i] < pivot)
                        i++;
                    while (array[j] > pivot)
                        j--;
                    if (i <= j)
                    {
                        temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                        i++;
                        j--;
                    }
                }
                if (j > low)
                    quickSort(array, low, j);
                if (i < high)
                    quickSort(array, i, high);
            }

            int main()
            {
                vector<int> array = {95, 45, 48, 98, 1, 485, 65, 478, 1, 2325};
                int n = sizeof(array)/sizeof(array[0]);

                cout << "Before Quick Sort :" << endl;
                printArray(array, n);

                quickSort(array, 0, n);

                cout << "After Quick Sort :" << endl;
                printArray(array, n);
                return (0);
            }

您正在按值將向量傳遞給quicksort函數,這會使它對輸入向量的副本進行操作(因此原始向量保持不變)。 一個可能的解決方案是通過引用傳遞它。 因此, quicksort的聲明應為:

void quickSort(std::vector<int> &array, int low, int high)

代碼的另一個問題是sizeof(array)/sizeof(array[0])不是獲取向量大小的正確方法,有效的方法是使用std::vector::size()方法(正如H. Guijt的回答中指出的那樣)

  1. 您正在按值傳遞數組,因此您在quicksort函數中對其進行的任何更改將對調用者不可見。 而是通過引用傳遞它。
  2. sizeof將返回向量控制塊的大小,而不是其存儲的字節數。 使用vector :: size()獲取元素數。

獎勵:使用std :: swap代替該temp變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM