sorting list to ascending and descending order

i have tried 2 methods but didnt work for me. they only work if i have input element before i run the program. for my program it only gets the elements when i run it.

i want to sort int i only, not the others.

first method:

struct myStruct {
int i;
int j;
int k;
};

bool compare(const myStruct& first, const myStruct& second)
{
if (first.i < second.i)
return true;
else
return false;
}

int main()
{
sort(compare);
}

error is no matching function to call to sort(unresolved overloaded function type)
is bool compare function getting anything from myStruct? or i am using the sort wrongly

std::sort requires two iterators, or two iterators and a function reference.
http://www.cplusplus.com/reference/algorithm/sort/

You're getting an error because your call to sort does not match either of the two std::sort calls.


i tried sort(myStruct.begin(),myStruct.end(),compare);

still not working
no matching function call to sort(std::list()<myStruct>::iterator)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <list>

struct myStruct
{
    int i;
    int j;
    int k;
};

bool compare_a( const myStruct& first, const myStruct& second )
{ return first.i < second.i ; }

bool compare_d( const myStruct& first, const myStruct& second )
{ return first.i > second.i ;  }

int main()
{
   std::list<myStruct> seq = { { 5, 1, 0 }, { 1, 2, 3 }, { 3, 0, 0 } } ;
   seq.sort(compare_a) ; // sort on ascending i
   seq.sort(compare_d) ; // sort on descending i
}
i can do it with predefined element in my list of structure. but my program runs and get the element from a txtfile then i can sort it out.

so i need myStruct.begin(),myStruct.end() in my sort but its not working
Topic archived. No new replies allowed.