【问题标题】:What is the use of swap() function in priority_queue class in C++?C ++中priority_queue类中swap()函数的用途是什么?
【发布时间】:2018-07-22 17:21:30
【问题描述】:

我正在探索 C++ 中的 priority_queue 类,但无法考虑 swap() 的任何实际用途。

参考:http://www.cplusplus.com/reference/queue/priority_queue/swap/

谁能列出一个使用此功能有益的实际示例。本质上,这感觉就像重命名优先级队列变量。

std::priority_queue<int> foo,bar;
foo.push (15); foo.push(30); foo.push(10);
bar.push (101); bar.push(202);

foo.swap(bar);

std::cout << "size of foo: " << foo.size() << '\n';
std::cout << "size of bar: " << bar.size() << '\n';

【问题讨论】:

  • 可能主要具有历史意义。 swap 是穷人的 move C++ 11 之前的版本。所有容器都有它,它不是priority_queue 独有的。那时,您可以像这样将一个元素“移动”到一个向量中:std::vector&lt;std::priority_queue&lt;int&gt; &gt; v; v.push_back(std::priority_queue&lt;int&gt;()); v.back().swap(myQueue);
  • '复制和交换'是一个众所周知的用于实现复制分配的习语。出于这个原因(以及其他原因),能够有效地交换对象很有用。
  • 如果你有一个类,它包含一个优先级队列作为成员,你的类可能是一个向量元素,你的类可能有一个交换成员函数(供 std::种类)。该交换成员函数可能会在实现中调用优先级队列交换。

标签: c++11 data-structures stl priority-queue swap


【解决方案1】:

swap 是库范围的功能;标准库中的许多类都支持交换。这也是一个定制点;您可以为自己的课程专门 std::swap

至于它的用途 - 有很多算法使用它(例如所有的排序算法),并且一些容器在内部使用它。

swapnoexcept 是编写异常安全代码的绝佳工具。

【讨论】:

    猜你喜欢
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2021-03-31
    • 2010-09-09
    相关资源
    最近更新 更多