sorting elements in the container

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typedef struct TGM{
        double numbers ;
        double SecondNumbers;
        bool negative;
}TGM;

    vector <TGM> tgms;
    TGM tgm;

for (; firstLoop != firstLoop_end; ++firstLoop) {
    for (; myNumbers != myNumbers_end; ++myNumbers) {
                tgm.numbers = myNumbers->value();
                tgm.SecondNumbers = SecondNumbers->value();
                if (myNumbers->value() < 0) tgm.negative = true;
    }
    tgms.push_back(tgm);
}


when I loop over the vector it prints the values of the numbers without any sorting method.
1
2
3
        for(unsigned int i=0; i < tgms.size(); ++i) {
              std::cout << tgms[i].numbers << std::endl;
        }


how can I sort the numbers from lowest to the highest value ?

I found something like for the vectors
1
2
3
vector<double> numbers;
// fill numbers somehow
std::sort(numbers.begin(), numbers.end());


but I have two different numbers in my struct, numbers and SecondNumbers.
how can I sort the numbers ? and how can I sort the SecondNumbers ?

thanks.


Last edited on
The first place to look is to see how the std::sort() routine works.
http://www.cplusplus.com/reference/algorithm/sort/

You will see that you can explicitly provide a function to compare the elements.

1
2
3
4
bool TGM_less_than( const TGM& lhs, const TGM& rhs )
  {
  return lhs.numbers < rhs.numbers;
  }
 
sort( tgms.begin(), tgms.end(), TGM_less_than );

If you want to preserve order when elements are equal, use std::stable_sort().

If you will always compare a TGM by the numbers, you can rewrite that special routine as an operator:
1
2
3
4
bool operator < ( const TGM& lhs, const TGM& rhs )
  {
  return lhs.numbers < rhs.numbers;
  }
 
sort( tgms.begin(), tgms.end() );

Hope this helps.
it works, thanks !
It's not a big deal but by looking this example; http://www.cplusplus.com/reference/algorithm/min_element/

I've tried to find the minimum element and do

std::cout << "Min = " << *min_element( tgms.begin(), tgms.end(), TGM_less_than ) << std::endl;

but doesn't work. I wonder what is wrong ?

It is probably because you don't have the insertion operator (operator <<) defined for your TGMs. Did you mean this instead?

 
cout << "Min = " << min_element( tgms.begin(), tgms.end(), TGM_less_than )->numbers << endl;
yes ! it's fine.
Topic archived. No new replies allowed.