how to sort std::vector<double>?
Hi,
I have a vector of doubles (std::vector<doubles>). All I want to do is sort this into an order where the first element has the highest value, the second element the second highest value...the last element the lowest value. The only promising thing I find is std::sort. But I cannot find any documentation on what it does. So I made a test: std::vector<Double_t> test; test.push_back(1); test.push_back(2); std::cout << "test[0] is " << test[0] << std::endl; std::cout << "test[1] is " << test[1] << std::endl; std::cout << "" << std::endl; std::sort(test.begin(),test.end()); std::cout << "test[0] is " << test[0] << std::endl; std::cout << "test[1] is " << test[1] << std::endl; std::cout << "next event " << std::endl; and this has output: test[0] is 1 test[1] is 2 test[0] is 1 test[1] is 2 next event so whatever sort does it doesnt reorder according to highest value. Is there a standard c++ function to do this to a std::vector? Thanks, Mark |
Well, std::sort (and std::stable_sort) sorts all elements in the supplied range using operator < (less than). So if you want to sort using > (greater than), you can supply your own comparison function. The following program examplies:
Code:
#include <algorithm> Code:
1.2 |
check here .
|
Just to provide another way of doing it (though I agree the custom comparor is the best way)..
Code:
#include <iostream> |
Thanks for all the help. I solved my problem now.
Cheers, Mark |
All times are GMT -5. The time now is 12:54 PM. |