如何找到地图的中间元素??STL

how to find the middle element of the map?? STL

本文关键字:元素 STL 中间 何找 地图      更新时间:2023-10-16

嗨,我陷入了STL库/C++中Map的概念之间。

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 << " ";
}

现在,当我打印这张地图时,它是按排序顺序打印的。现在有什么最简单的方法可以找到这张地图的中间吗。。。。。需要找到一个更大问题的中位数。。。因此,尝试实现平衡的二进制搜索树。。

map一个平衡的搜索树。要找到它的中间——找到它的大小,并从begin()迭代它大小的一半——这将是中间。类似这样的东西:

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来排序,那就太过分了,IMHO。使用数组(或vector)可以更有效地实现这一点,然后找到中间值也很简单。map用于按键访问数据,而不仅仅是排序。

在显示的代码中,您正在滥用映射来对键进行排序。

您可以获得更多的性能,避免完全排序和复制:

   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;

std::map可能不是定位中值的最佳容器。但这很简单:

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

std::映射不能在一次拍摄中为您提供中值。如果你想要中位数,你需要使用这个算法。