Efficient way to get middle (median) of an std::set?

后端 未结 5 1723
故里飘歌
故里飘歌 2021-01-07 23:52

std::set is a sorted tree. It provides begin and end methods so I can get minimum and maximum and lower_bound and u

5条回答
  •  無奈伤痛
    2021-01-08 00:28

    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.

提交回复
热议问题