cpp std::sort array, the default sort order is ascending

//.model/util.h
template<typename T>
    T get_random_num(T min,T max)
    {
        std::random_device rd;
        std::mt19937_64 mt(rd());
        std::uniform_int_distribution<T> uid(min,max);
        return uid(mt);
    }

    template<typename T>
    void fill_T_array(T min, T max,T *arr,int len)
    {
        for(int i=0;i<len;i++)
        {
            arr[i]=get_random_num(min,max);
        }
    }

    template<typename T>
    void print_T_array(T *arr,int len=0)
    {
        for(int i=0;i<len;i++)
        {
            std::cout<<arr[i]<<"\t";
        }
        std::cout<<std::endl<<std::endl;
    }

    void fill_print_T_demo(int len);

    template<typename T>
    void swap_t(T *left,T *right)
    {
        T temp=*left;
        *left=*right;
        *right=temp;
    }

    template<typename T>
    int partition_array(T* arr,int low,int high)
    {
        T pivot=arr[high];
        int i=low-1;
        for(int j=low;j<high;j++)
        {
            if(arr[j]<pivot)
            {
                i=i+1;
                swap_t(&arr[i],&arr[j]);
            }
        }
        swap_t(&arr[i+1],&arr[high]);
        return i+1;
    }

    template<typename T>
    void quick_sort_T(T *arr,int low,int high)
    {
        if(low<=high)
        {
            int pivot=partition_array(arr,low,high);
            quick_sort_T(arr,low,pivot-1);
            quick_sort_T(arr,pivot+1,high);
        }
    } 

    template<typename T>
    void std_sort(T *arr,int len)
    {
        std::sort(arr,arr+len,std::greater<T>());
        print_T_array(arr,len);
    }

    void std_sort_demo(int len);


void util::std_sort_demo(int len)
{
    std::uint32_t *arr = new std::uint32_t[len];
    fill_T_array<std::uint32_t>(0, UINT32_MAX, arr, len);
    std::cout << "Before std sort:" << std::endl;
    print_T_array(arr, len);
    std::cout << "After std sort:" << std::endl;
    std_sort(arr, len);
    print_log("finished in " + std::string(__FUNCTION__) + ",line " + std::to_string(len));
}


//main.cpp

void std_sort_demo(int len)
{
    util ul;
    ul.std_sort_demo(len);
}

int main(int args, char **argv)
{    
   std_sort_demo(atoi(argv[1]));
}

 

 

The key code is

template<typename T>
    void std_sort(T *arr,int len)
    {
        std::sort(arr,arr+len,std::greater<T>());
        print_T_array(arr,len);
    }

 

 

Compile

g++ -I. *.cpp ./model/*.cpp -o h1 -luuid

 

 

Run

./h1 100

 

 

 

 

When order the array via std::sort default method it will sort ascendingly

 template<typename T>
    void std_sort(T *arr,int len)
    {
        std::sort(arr,arr+len);
        print_T_array(arr,len);
    }

 

 

posted @ 2023-02-26 15:02  FredGrit  阅读(21)  评论(0编辑  收藏  举报