如何找到地图的中间元素??STL
how to find the middle element of the map?? STL
嗨,我陷入了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::映射不能在一次拍摄中为您提供中值。如果你想要中位数,你需要使用这个算法。
相关文章:
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- 是否有具有外部元素分配的序列容器(在 STL 中)?
- 擦除是否删除 stl 无序列图元素使用的堆内存
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何将元素从 STL 队列传递到函数?
- 如果键不存在,使用 [] 运算符访问 STL Map 元素会添加新元素
- 如何在非STL图中找到最小的元素?
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 无法在STL中打印一组矢量的元素
- 如果我想从类型"T"定义元素的容器(来自 STL),那么"T"必须使用默认构造函数?
- 使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
- 如何使用 STL 哈希容器中的哈希值检索元素?
- 打印/修改类对象的特定成员变量,其类定义列表 (STL) 包含的元素类型
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- lower_bound 在 C++ STL 中返回迭代器,即使元素不存在也是如此.如何避免这种情况?
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- 直接访问 STL "set"元素
- 无法将元素添加到 STL 映射
- 如何找到地图的中间元素??STL