std::set
is a sorted tree. It provides begin
and end
methods so I can get minimum and maximum and lower_bound
and u
Be aware that the std::set
does NOT store duplicate values. If you insert the following values {1, 2, 3, 3, 3, 3, 3, 3, 3}
, the median you will retrieve is 2
.
std::set::iterator it = s.begin();
std::advance(it, s.size() / 2);
int median = *it;
If you want to include duplicates when considering the median you can use std::multiset
({1, 2, 3, 3, 3, 3, 3, 3, 3}
median's would be 3
) :
std::multiset::iterator it = s.begin();
std::advance(it, s.size() / 2);
int median = *it;
If the only reason you want the data sorted is to get the median, you are better off with a plain old std::vector
+ std::sort
in my opinion.
With a large test sample and multiple iterations, I completed the test in 5s with std::vector
and std::sort
and 13 to 15s with either std::set
or std::multiset
. Your milage may vary depending on the size and number of duplicate values you have.