跳到主要内容

std::priority_queue push() 方法

// (1) Non const version only
void push( const value_type& value );

// (2) Non const version only
void push( value_type&& value );

将给定的元素值推送到优先队列的末尾。

  • (1) 实际上调用
    c.push_back(value);
    std::push_heap(c.begin(), c.end(), comp);
  • (1) 实际上调用
    c.push_back(std::move(value));
    std::push_heap(c.begin(), c.end(), comp);

参数

  • value - 要推入的元素的值

返回值

(无)

复杂度

对底层容器的 push_back 操作的对数级比较次数加上其复杂度。

示例

Main.cpp
#include <queue>
#include <iostream>

struct Event
{
int priority{};
char data{' '};

friend bool operator< (Event const& lhs, Event const& rhs) {
return lhs.priority < rhs.priority;
}

friend std::ostream& operator<< (std::ostream& os, Event const& e) {
return os << "{ " << e.priority << ", '" << e.data << "' } ";
}
};

int main()
{
std::priority_queue<Event> events;

std::cout << "Fill the events queue:\n";

for (auto const e: { Event{6,'L'}, {8,'I'}, {9,'S'}, {1,'T'}, {5,'E'}, {3,'N'} }) {
std::cout << e << ' ';
events.push(e);
}

std::cout << "\n" "Process events:\n";

for (; !events.empty(); events.pop()) {
Event const& e = events.top();
std::cout << e << ' ';
}
}
输出
Fill the events queue:
{ 6, 'L' } { 8, 'I' } { 9, 'S' } { 1, 'T' } { 5, 'E' } { 3, 'N' }
Process events:
{ 9, 'S' } { 8, 'I' } { 6, 'L' } { 5, 'E' } { 3, 'N' } { 1, 'T' }

std::priority_queue push() 方法

// (1) Non const version only
void push( const value_type& value );

// (2) Non const version only
void push( value_type&& value );

将给定的元素值推送到优先队列的末尾。

  • (1) 实际上调用
    c.push_back(value);
    std::push_heap(c.begin(), c.end(), comp);
  • (1) 实际上调用
    c.push_back(std::move(value));
    std::push_heap(c.begin(), c.end(), comp);

参数

  • value - 要推入的元素的值

返回值

(无)

复杂度

对底层容器的 push_back 操作的对数级比较次数加上其复杂度。

示例

Main.cpp
#include <queue>
#include <iostream>

struct Event
{
int priority{};
char data{' '};

friend bool operator< (Event const& lhs, Event const& rhs) {
return lhs.priority < rhs.priority;
}

friend std::ostream& operator<< (std::ostream& os, Event const& e) {
return os << "{ " << e.priority << ", '" << e.data << "' } ";
}
};

int main()
{
std::priority_queue<Event> events;

std::cout << "Fill the events queue:\n";

for (auto const e: { Event{6,'L'}, {8,'I'}, {9,'S'}, {1,'T'}, {5,'E'}, {3,'N'} }) {
std::cout << e << ' ';
events.push(e);
}

std::cout << "\n" "Process events:\n";

for (; !events.empty(); events.pop()) {
Event const& e = events.top();
std::cout << e << ' ';
}
}
输出
Fill the events queue:
{ 6, 'L' } { 8, 'I' } { 9, 'S' } { 1, 'T' } { 5, 'E' } { 3, 'N' }
Process events:
{ 9, 'S' } { 8, 'I' } { 6, 'L' } { 5, 'E' } { 3, 'N' } { 1, 'T' }