best way to go about this?

i have a group of random numbers ranging from 1 - 10000 in a list, i want to arrange that whole list by descending order, what is the best ways to do this?
list is able to sort itself: http://www.cplusplus.com/reference/stl/list/sort/ , although for descending order, you will need to use something like std::greater as the sorting predicate

i want to sort by comparing pIndex->ValueToCompare, how is that done by sort??
Last edited on
Here's a working example (works with gcc and clang++, but the function Pred will work in any compiler)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <list>
#include <random>

int GenrateRandNumber(int min, int max)
{
    static std::random_device seed;
    static std::mt19937 gen(seed());
    return std::uniform_int_distribution<>(min, max)(gen);
}

struct  RANDOM_NUMBERORDER
{
        short   sIndex;
        int ValueToCompare;
};

bool Pred(const RANDOM_NUMBERORDER* left, const RANDOM_NUMBERORDER* right)
{
    return left->ValueToCompare > right->ValueToCompare;
}

int main()
{
    std::list<RANDOM_NUMBERORDER*> m_ComparationList;
    int i=0;

    while(i < 10000)
    {
        RANDOM_NUMBERORDER* pIndex = new RANDOM_NUMBERORDER;
        pIndex->sIndex = i;
        pIndex->ValueToCompare = GenrateRandNumber(1, 10000);
        m_ComparationList.push_back(pIndex);
        i++;
    }

    m_ComparationList.sort(Pred);

    for(auto p: m_ComparationList)
    {
        std::cout << p->ValueToCompare << ' ';
        delete p;
    }

}
Last edited on
any other alternatives?
Last edited on
Use sort() function. Assuming you are using STL's list and the number in your list is "int" type.


bool func(int x, int y)
{
return x<y;
}

sort(list.begin(), list.end(), func);


b2ee
Topic archived. No new replies allowed.