How to find the middle element of the map? STL

Hi, I am stuck between the concept of Map in STL Library / C ++.

int arr[] = {10,15,14,13,17,15,16,12,18,10,29,24,35,36};
int n = sizeof arr / sizeof *arr;

map<int, bool> bst;
map<int, bool>::iterator it;
vector<int> median_output;

const int k = 5;
for (int i = 0; i < k; ++i) {
    bst.insert(make_pair(arr[i], true));
}

for (it = bst.begin(); it != bst.end(); it++) {
    cout << (*it).first << " ";
}

Now that I printed this card, it was printed in sorted order. Now there is some simple way to find the middle of this map ..... We need to find the median big problem ... Therefore, we are trying to implement a balanced binary search tree.

+5
source share
4 answers

map balanced search tree. To find it in the middle - find its size and iterate with begin()for half its size - this will be the middle. Something like that:

for (it = bst.begin(), int middle = 0; middle < bst.size()/2; it++, middle++) {
    cout << (*it).first << " ";
}

// now after the loop it is the median.

map , , . ( vector), . map , .

+5

.

, :

   const int len = 14;
   const int a[len] = {10,15,14,13,17,15,16,12,18,10,29,24,35,36};

   std::nth_element( a, a+len/2, a+len );
   std::cout << "Median: " << a[len/2] << std::endl;

STL, ( , ):

   std::vector<int> v( a, a+len );
   std::nth_element( v.begin(), v.begin()+len/2,v.end() );
   std::cout << "Median: " << v[len/2] << std::endl;
+4

std::map . :

it = bst.begin();
advance( it, bst.size() / 2);
cout << endl << "median: " << it->first << endl;
+2

std:: maps . , .

0

All Articles