How to find the middle element in std::set with an odd number of elements?

  • 2
    What is the “middle element” for you and what is the specific problem? - αλεχολυτ
  • @alexolut item with index mySet.size()/2 - user237432
  • There are no indices in std::set . - αλεχολυτ

2 answers 2

You probably need something like this:

 std::set<какой_то_тип> s; // ... auto iter = s.cbegin(); std::advance(iter, s.size() / 2); 

It uses std::advance to move the iterator to the specified number of positions.

  • Another would be to know - why. - αλεχολυτ
  • excellent, thanks - user237432 February
  • @alexolut finding the middle element is quite a frequent task, so the time constant is better than when sorting an array - user237432
  • four
    @ user237432 You are using set not for the intended purpose, if you have such a problem. set is a set, used when you need to store information about the presence of any element. Position is generally not important. If position is important, you should prefer another container, for example, vector . - αλεχολυτ
  • @alexolut: Well, this is usually needed to find the 50% quantile of any data sample. - VladD

This can be done by sequential iteration using the class iterator, since the standard class std::set does not have random access iterators, but has two-way iterators. For example,

 #include <iostream> #include <iterator> #include <set> int main() { std::set<int> s = { 1, 2, 3, 4, 5, 6, 7 }; int middle = *std::next( s.begin(), s.size() / 2 ); std::cout << middle << std::endl; } 

Output of the program to the console

 4 
  • imkho, std::advance() better reflects intentions - user237432
  • one
    @ user237432 To do this, you will have to clutter up the namespace with a new name to store the iterator, which is essentially used in only one time expression. - Vlad from Moscow