本文整理汇总了C++中std::priority_queue类的典型用法代码示例。如果您正苦于以下问题:C++ priority_queue类的具体用法?C++ priority_queue怎么用?C++ priority_queue使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了priority_queue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: merge
void AggregatingSortedBlockInputStream::merge(MutableColumns & merged_columns, std::priority_queue<SortCursor> & queue)
{
size_t merged_rows = 0;
/// We take the rows in the correct order and put them in `merged_block`, while the rows are no more than `max_block_size`
while (!queue.empty())
{
SortCursor current = queue.top();
setPrimaryKeyRef(next_key, current);
bool key_differs;
if (current_key.empty()) /// The first key encountered.
{
setPrimaryKeyRef(current_key, current);
key_differs = true;
}
else
key_differs = next_key != current_key;
/// if there are enough rows accumulated and the last one is calculated completely
if (key_differs && merged_rows >= max_block_size)
return;
queue.pop();
if (key_differs)
{
current_key.swap(next_key);
/// We will write the data for the group. We copy the values of ordinary columns.
for (size_t i = 0, size = column_numbers_not_to_aggregate.size(); i < size; ++i)
{
size_t j = column_numbers_not_to_aggregate[i];
merged_columns[j]->insertFrom(*current->all_columns[j], current->pos);
}
/// Add the empty aggregation state to the aggregate columns. The state will be updated in the `addRow` function.
for (auto & column_to_aggregate : columns_to_aggregate)
column_to_aggregate->insertDefault();
++merged_rows;
}
addRow(current);
if (!current->isLast())
{
current->next();
queue.push(current);
}
else
{
/// We fetch the next block from the appropriate source, if there is one.
fetchNextBlock(current, queue);
}
}
finished = true;
}
示例2: AddToHeaps
void AddToHeaps(std::priority_queue<double, std::vector<double>, std::greater<double> >& m,
std::priority_queue<double>& M, double x){
// decide on initial heap to place element into
if(m.empty() || x < m.top())
M.push(x);
else
m.push(x);
// make sure that heaps are balanced
if(m.size() > M.size() + 1){
M.push( m.top() );
m.pop();
}
else if(M.size() > m.size() + 1){
m.push( M.top() );
M.pop();
}
}
示例3: dijkstra_pq_thread
void dijkstra_pq_thread(CSRGraph *g, int *dist, std::priority_queue<Priority_struct, std::vector<Priority_struct>, Compare_priority> &pq, int threadNum, std::mutex *dist_locks)
{
while(!pq.empty())
{
queue_lock.lock();
if(pq.empty())
{
queue_lock.unlock();
break;
}
Priority_struct temp_struct = pq.top();
int u = temp_struct.node_name;
pq.pop();
printf("Popped\n");
for(int i=0; i< pq.size();i++){
printf(" %d", pq[i]);
}
printf("\n");
int udist = dist[u];
queue_lock.unlock();
std::vector<int> neighbors = CSRGraph_getNeighbors(g, u);
int neighbor;
for(neighbor=0;neighbor < neighbors.size(); neighbor++)
{
int v = neighbors[neighbor];
int uvdist = CSRGraph_getDistance(g, u, v);
int alt = udist + uvdist;
dist_locks[v].lock();
if(alt < dist[v])
{
dist[v] = alt;
dist_locks[v].unlock();
Priority_struct temp2;
temp2.node_name=v;
temp2.node_weight = uvdist;
queue_lock.lock();
pq.push(temp2);
printf("Pushed\n");
for(int i=0; i< pq.size();i++){
printf(" %d", pq[i]);
}
printf("\n");
queue_lock.unlock();
}
else
{
dist_locks[v].unlock();
}
}
}
//printf("Thread %d ended.\n", threadNum);
}
示例4: merge
void MergingSortedBlockInputStream::merge(Block & merged_block, ColumnPlainPtrs & merged_columns, std::priority_queue<TSortCursor> & queue)
{
size_t merged_rows = 0;
/** Увеличить счётчики строк.
* Вернуть true, если пора закончить формировать текущий блок данных.
*/
auto count_row_and_check_limit = [&, this]()
{
++total_merged_rows;
if (limit && total_merged_rows == limit)
{
// std::cerr << "Limit reached\n";
cancel();
finished = true;
return true;
}
++merged_rows;
if (merged_rows == max_block_size)
{
// std::cerr << "max_block_size reached\n";
return true;
}
return false;
};
/// Вынимаем строки в нужном порядке и кладём в merged_block, пока строк не больше max_block_size
while (!queue.empty())
{
TSortCursor current = queue.top();
queue.pop();
while (true)
{
/** А вдруг для текущего курсора блок целиком меньше или равен, чем остальные?
* Или в очереди остался только один источник данных? Тогда можно целиком взять блок текущего курсора.
*/
if (current.impl->isFirst() && (queue.empty() || current.totallyLessOrEquals(queue.top())))
{
// std::cerr << "current block is totally less or equals\n";
/// Если в текущем блоке уже есть данные, то сначала вернём его. Мы попадём сюда снова при следующем вызове функции merge.
if (merged_rows != 0)
{
// std::cerr << "merged rows is non-zero\n";
queue.push(current);
return;
}
/// Actually, current.impl->order stores source number (i.e. cursors[current.impl->order] == current.impl)
size_t source_num = current.impl->order;
if (source_num >= cursors.size())
throw Exception("Logical error in MergingSortedBlockInputStream", ErrorCodes::LOGICAL_ERROR);
for (size_t i = 0; i < num_columns; ++i)
merged_block.getByPosition(i).column = source_blocks[source_num]->getByPosition(i).column;
// std::cerr << "copied columns\n";
size_t merged_rows = merged_block.rows();
if (limit && total_merged_rows + merged_rows > limit)
{
merged_rows = limit - total_merged_rows;
for (size_t i = 0; i < num_columns; ++i)
{
auto & column = merged_block.getByPosition(i).column;
column = column->cut(0, merged_rows);
}
cancel();
finished = true;
}
if (out_row_sources)
out_row_sources->resize_fill(out_row_sources->size() + merged_rows, RowSourcePart(source_num));
// std::cerr << "fetching next block\n";
total_merged_rows += merged_rows;
fetchNextBlock(current, queue);
return;
}
// std::cerr << "total_merged_rows: " << total_merged_rows << ", merged_rows: " << merged_rows << "\n";
// std::cerr << "Inserting row\n";
for (size_t i = 0; i < num_columns; ++i)
merged_columns[i]->insertFrom(*current->all_columns[i], current->pos);
if (out_row_sources)
{
/// Actually, current.impl->order stores source number (i.e. cursors[current.impl->order] == current.impl)
out_row_sources->emplace_back(current.impl->order);
}
if (!current->isLast())
{
//.........这里部分代码省略.........
示例5: initQueue
void MergingSortedBlockInputStream::initQueue(std::priority_queue<TSortCursor> & queue)
{
for (size_t i = 0; i < cursors.size(); ++i)
if (!cursors[i].empty())
queue.push(TSortCursor(&cursors[i]));
}
示例6: merge
void AggregatingSortedBlockInputStream::merge(ColumnPlainPtrs & merged_columns, std::priority_queue<TSortCursor> & queue)
{
size_t merged_rows = 0;
/// Вынимаем строки в нужном порядке и кладём в merged_block, пока строк не больше max_block_size
while (!queue.empty())
{
TSortCursor current = queue.top();
setPrimaryKeyRef(next_key, current);
bool key_differs;
if (current_key.empty()) /// Первый встретившийся ключ.
{
current_key.columns.resize(description.size());
setPrimaryKeyRef(current_key, current);
key_differs = true;
}
else
key_differs = next_key != current_key;
/// если накопилось достаточно строк и последняя посчитана полностью
if (key_differs && merged_rows >= max_block_size)
return;
queue.pop();
if (key_differs)
{
current_key.swap(next_key);
/// Запишем данные для очередной группы. Копируем значения обычных столбцов.
for (size_t i = 0, size = column_numbers_not_to_aggregate.size(); i < size; ++i)
{
size_t j = column_numbers_not_to_aggregate[i];
merged_columns[j]->insertFrom(*current->all_columns[j], current->pos);
}
/// Добавляем в агрегатные столбцы пустое состояние агрегации. Состояние будет обновлено в функции addRow.
for (auto & column_to_aggregate : columns_to_aggregate)
column_to_aggregate->insertDefault();
++merged_rows;
}
addRow(current);
if (!current->isLast())
{
current->next();
queue.push(current);
}
else
{
/// Достаём из соответствующего источника следующий блок, если есть.
fetchNextBlock(current, queue);
}
}
finished = true;
}
示例7: pintar_vertices
void pintar_vertices(Grafo& g, std::priority_queue<Vertice, std::vector<Vertice>, std::greater<Vertice> >& vertices) { //std::priority_queue<Vertice> vertices) {
init_time();
int vistos = 0;
int cant_vertices = g.cant_vertices();
// Creo vector para obtener el maximo
for (int i = 0 ; i < cant_vertices ; ++i) {
vertices.push(g.dame_vertice(i));
}
// Recorro todos los vertices del grafo
while (vistos < cant_vertices) {
//std::cout << "vistos: " << vistos << " cant_vertices " << cant_vertices << std::endl;
// Hallar el vertice de mayor grado
Vertice vertice = vertices.top();
// std::cout << "vertice: " << vertice.dame_nombre() << std::endl;
vertices.pop();
std::set<int> colores_vertice = vertice.dame_colores_posibles();
// Creo un diccionario para ver cual es el color
// que mas usan los vecinos
// y otro para ver cual es el que mas se repite entre los
// colores posibles de los vecinos
std::map<int, int> colores_usados;
std::map<int, int> colores_posibles;
for (int color : colores_vertice) {
colores_usados.insert(std::pair<int, int> (color, 0));
colores_posibles.insert(std::pair<int, int> (color, 0));
}
// recorro los vecinos del maximo
std::set<int> vecinos = g.dame_vecinos(vertice.dame_nombre());
for (int v : vecinos) {
int color_vecino = g.dame_color(v);
if (color_vecino != -1) { // Ya esta pintado el vecino y no puedo usar ese color
// Me fijo si el vertice sobre el cual estoy parado tiene a ese
// color como disponible y de ser así lo aumento en el diccionario de colores
std::set<int>::iterator it = colores_vertice.find(color_vecino);
if (it != colores_vertice.end())
colores_usados[color_vecino]++;
} else {
// Si no esta pintado el vecino
std::set<int> colores_vecino = g.dame_colores_posibles(v);
// Por cada color que entre en conflicto sumo 1 en el diccionario
for (int color : colores_vecino) {
std::set<int>::iterator it = colores_vertice.find(color);
if (it != colores_vertice.end()) {
colores_posibles[color]++;
}
}
}
}
// Tengo dos diccionarios que determinan para cada color que tiene el vértice
// la cantidad de vecinos que tienen ese color pintado
// y la cantidad de vecinos que tienen ese color como posibilidad
// Recorro el diccionario de colores usados por mis vecinos
for (int i = 0 ; i < colores_usados.size() ; ++i) {
if (colores_vertice.size() > 1) {
// Elijo el color que es el mas utilizado por mis vecinos
int color_con_mas_apariciones = dame_el_de_maxima_aparicion(colores_usados);
// Lo borro
if (color_con_mas_apariciones != -1 )
colores_vertice.erase(color_con_mas_apariciones);
}
}
// O salgo del for anterior con muchos colores disponibles porque mis vecinos no
// estaban pintados
// o tengo un único color disponible para pintarme
int color;
if (colores_vertice.size() == 1) {
// Si me queda un único color en mi conjunto es el que menos conflictos me causaba
// por ende pinto al grafo de esa manera
std::set<int>::iterator it = colores_vertice.begin();
color = *it;
} else {
// Si me queda más de un color disponible busco en los posibles colores
// de mis vecinos el que quizas me trae menos conflictos
int min = 999;
for (std::pair<const int, int>& par : colores_posibles) {
if (par.second < min) {
std::set<int>::iterator it = colores_vertice.find(par.first);
if (it != colores_vertice.end()) {
min = par.second;
color = par.first;
}
}
}
}
g.pintar(vertice.dame_nombre(), color);
//g.imprimir();
vistos++;
}
acum += get_time();
}
示例8: empty
/**
* Determine if no points are found
*
* @return True if no points added
*/
bool empty() const {
return m_q.empty();
}
示例9: get
inline T get() {
T best_item = elements.top().second;
elements.pop();
return best_item;
}
示例10: get_next
tripoint get_next() {
auto pt = open.top();
open.pop();
return pt.second;
}
示例11: empty
inline bool empty(void) const
{
return data.empty();
}
示例12: empty
inline bool empty() { return elements.empty(); }
示例13: checkCollision
void checkCollision() {
int i, j;
if ( events.size()!=0) {
while( elapsedTime >= events.top().timeOccuring)
{
i = events.top().i;
if( checkOutdated( events.top() ) ) {
printf("---POOPZIES of %d, timeInserted=%f, lastCollition=%f\n",
i, events.top().timeInserted, sphere[i].lastCollision );
events.pop();
} else if (events.top().j!=-1) {
j = events.top().j;
sphere[i].q0 += (events.top().timeOccuring - sphere[i].t0) * sphere[i].speedVec;
sphere[i].speedVec = sphere[i].newSpeedVec;
sphere[i].t0 = events.top().timeOccuring;
sphere[j].q0 += (events.top().timeOccuring - sphere[j].t0) * sphere[j].speedVec;
sphere[j].speedVec = sphere[j].newSpeedVec;
sphere[j].t0 = events.top().timeOccuring;
sphere[i].cols++;
sphere[j].cols++;
events.pop();
calculateCollision(i);
calculateCollision(j);
printf("BALLZIES of %d, timeInserted=%f, lastCollition=%f\n",
i, events.top().timeInserted, sphere[i].lastCollision );
} else {
sphere[i].q0 += (events.top().timeOccuring - sphere[i].t0) * sphere[i].speedVec;
sphere[i].speedVec = sphere[i].newSpeedVec;
sphere[i].t0 = events.top().timeOccuring;
sphere[i].cols++;
events.pop();
calculateCollision(i);
printf("WALLZIES of %d, timeInserted=%f, lastCollition=%f\n",
i, events.top().timeInserted, sphere[i].lastCollision );
}
}
//std::vector<Sphere>::iterator it = sphereIterInit;
//for(it; it != sphere.end();it++){
// position = it->q0 + (float)(elapsedTime - it->t0) * it->speedVec;
// if(abs(position.x)>0.96f || abs(position.y)>0.96f || abs(position.z)>0.96f){
// printf("WHAT THE FUCK MOAR BUGS PLS!!!!!AAAAAAAAAAARRGGH\n");
// }
//}
minmin = (events.top().timeOccuring<minmin)?events.top().timeOccuring:minmin;
}
}
示例15: top
Cell top() const
{
return _pq.top().cell;
}