简体   繁体   English

std::sort 函数不是对向量进行排序,我不知道为什么?

[英]std::sort function is not sorting a vector, and I don't know why?

I have written a code to implement the quicksort algorithm in c++, it is working but the std::sort() function is not working at all.我已经编写了一个代码来在 C++ 中实现快速排序算法,它正在工作,但 std::sort() 函数根本不工作。 Please explain to me why.请向我解释原因。

#include "header.h"

using namespace std;
using namespace std::chrono;
bool myfunction (int i,int j) { return (i<j); }
int Partition(vector<int>& A, int start, int end){
    int pivot_idx = (rand() % (end - start + 1)) + start;
    Xswap(A[pivot_idx], A[end]);
    int pivot = A[end];
    int P_index = start;
    for(int i=start; i < end; i++){
        if(A[i] <= pivot){
            Xswap(A[i], A[P_index]);
            P_index++;
        }
    }
    Xswap(A[P_index], A[end]);
    return P_index;
}

void Qsort(vector<int>& A, int start, int end){
    if(start < end){
        int middle = Partition(A, start, end);
        Qsort(A, start, middle-1);
        Qsort(A, middle+1, end);
    }
}

void quick_sort(void){
    srand(time(NULL));
    int n;
    cin >> n;
    vector<int> v;
    v.reserve(n);
    //v.shrink_to_fit();
    
    for(int i=0; i<n; i++)
        v[i] = rand() % 1000;
    
    /*for(int i=0; i<n; i++)
        cout << v[i] << " ";
    cout << endl << endl;*/
    auto start = high_resolution_clock::now(); 
    
    //Qsort(v, 0, n-1);
    sort(v.begin(), v.end(), myfunction);
    
    auto stop = high_resolution_clock::now(); 
    auto duration = duration_cast<microseconds>(stop - start);
    for(int i=0; i<n; i++)
        cout << v[i] << " ";
    cout << endl;
    cout << duration.count() << endl; 
}

If you want to know what output is being shown upon calling executing the snippet:如果您想知道在调用执行代码段时显示什么输出: 程序输出

And if you want to see the contents of the header file:如果你想查看头文件的内容:

#ifndef HEADER_H
#define HEADER_H

#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <chrono>
#include <time.h>
void bble_sort(void);
void improved_bble_sort(void);
void quick_sort(void);
void ins_sort(void);
void Qsort(std::vector<int>& A, int start, int end);

template <typename T>
void Xswap(T& a, T& b);

#endif /* HEADER_H */

The vector in the output is completely unsorted;输出中的向量是完全未排序的; I have tried range-based for loop and iterators but nothing helped out.我尝试过基于范围的 for 循环和迭代器,但没有任何帮助。 Please provide me some solutions or ideas, I'm completely confused.请为我提供一些解决方案或想法,我完全糊涂了。

std::vector::reserve is a hint to the container to enable fewer reallocations. std::vector::reserve是对容器的提示,以启用更少的重新分配。 It doesn't actually make v[5] valid.它实际上并没有使v[5]有效。 Instead, usestd::vector::resize() .相反,使用std::vector::resize()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM