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

后端 未结 5 1645
故里飘歌
故里飘歌 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:16

    If your data is static, those you could precalcate it and do not insert new elements - it’s simplier to use vector , sort it , and access median just by index in O(1)

    vector data;
    // fill data
    std::sort(data.begin(), data.end());
    auto median = data[data.size() / 2];
    

提交回复
热议问题