std:: swap (std::priority_queue)
|
定义于头文件
<queue>
|
||
|
template
<
class
T,
class
Container,
class
Compare
>
void
swap
(
std::
priority_queue
<
T, Container, Compare
>
&
lhs,
|
(C++11 起)
(C++17 前) |
|
|
template
<
class
T,
class
Container,
class
Compare
>
void
swap
(
std::
priority_queue
<
T, Container, Compare
>
&
lhs,
|
(C++17 起)
(C++26 起为 constexpr) |
|
|
此重载仅当 std:: is_swappable_v < Container > 与 std:: is_swappable_v < Compare > 均为 true 时参与重载决议。 |
(since C++17) |
目录参数
复杂度等同于交换底层容器。 异常处理
注释虽然容器适配器的 std::swap 重载是在C++11中引入的,但在C++98中容器适配器已经可以通过 std::swap 进行交换。此类对 std::swap 的调用通常具有线性时间复杂度,但也可能提供更优的时间复杂度。 示例
运行此代码
#include <algorithm> #include <iostream> #include <queue> int main() { std::priority_queue<int> alice; std::priority_queue<int> bob; auto print = [](const auto& title, const auto& cont) { std::cout << title << " size=" << cont.size(); std::cout << " top=" << cont.top() << '\n'; }; for (int i = 1; i < 4; ++i) alice.push(i); for (int i = 7; i < 11; ++i) bob.push(i); // 交换前的状态打印 print("Alice:", alice); print("Bobby:", bob); std::cout << "-- SWAP\n"; std::swap(alice, bob); // 交换后的状态打印 print("Alice:", alice); print("Bobby:", bob); } 输出: Alice: size=3 top=3 Bobby: size=4 top=10 -- SWAP Alice: size=4 top=10 Bobby: size=3 top=3 参见
|