哪个c++ STL容器提供了' extract_max() ', ' find(element_value) '

Which C++ STL container provides `extract_max()`, `find(element_value)` and `modify(element)` functionality?

本文关键字:max find value element extract STL c++ 哪个      更新时间:2023-10-16

我想使用c++ STL容器来实现Prim的算法。我需要extract_max, find(element)modify(element_value)的功能,但std::priority_queue只提供extract_max。有没有其他的容器可以用?显然,我希望所有这些都尽可能快。

编辑:容器还应该提供修改其元素值的功能。

将元素推入std::set<T, std::greater<T>>,这是一个有序堆。

  • 调用*set::begin()以在O(1)或O(log(n))上获得最大元素,具体取决于set::begin()的实现方式。
  • 使用set::find在O(log(n))内执行搜索
  • 要修改一个元素,不幸的是,您必须将其从集合中删除,然后插入修改后的版本。(这也适用于make_heap和好友)。可能存在不需要这样做的答案,但是(A)您必须偏执于使用哪些成员进行比较和相等,以及(B)速度差异非常小。所以没有通用的容器是这样工作的。
  • 如果元素的顺序不是唯一的,则使用std::multiset代替,否则是相同的。

的例子:

#include <iostream>
#include <set>
int main()
{
    std::set<int, std::greater<int>> v { 3, 1, 4, 1, 5, 9 };
    std::cout << "initially, v: ";
    for (auto i : v) std::cout << i << ' ';
    std::cout << 'n';
    auto largest = *v.begin();
    v.erase(v.begin());
    std::cout << "largest element: " << largest << 'n';
    std::cout << "after removing the largest element, v: ";
    for (auto i : v) std::cout << i << ' ';
    std::cout << 'n';
}

现场演示