gpt4 book ai didi

c++ - Priority_queue 和输入流迭代器

转载 作者:行者123 更新时间:2023-11-27 23:24:12 26 4
gpt4 key购买 nike

int main()
{
list<char> letters;
priority_queue<char, vector<char>, less<char>>letters_trans;

cout << "Enter some sentence: " << endl << endl;

std::istream_iterator<char> input(cin), input_end;

copy(input, input_end, back_inserter<list<char>>(letters));

for each(char letter in letters)
{
letters_trans.push(letter);
}

while(!letters_trans.empty())
{
cout << letters_trans.top();
letters_trans.pop();
}
cout << endl;
getch();
return 0;
}

如您所见,我有一个学校项目将 cin 转移到优先队列。好吧,我“有点做到了……我所做的是输入 istream_iterator 来列出

,然后输入 priority_queue,我想从长远来看这是非常低效的。那么有没有办法转移直接 cin 到 priority_queue,没有中间人。我试过这样做,但复制功能不允许我将 priority_queue 作为参数。

最佳答案

您可以从一对迭代器 [first, last) 构建 priority_queue(或任何标准容器)。来自 cpp reference :

template <class InputIterator>
priority_queue ( InputIterator first, InputIterator last,
const Compare& x = Compare(),
const Container& y = Container() );

first,last

Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last. The function template type can be any type of input iterator.

代码:

#include <iostream>
#include <iterator>
#include <queue>
#include <vector>

int main()
{
std::istream_iterator<char, std::vector<char> > input(std::cin), input_end;
std::priority_queue<char> q(input, input_end);

while (!q.empty())
{
std::cout << q.top() << std::endl;
q.pop();
}
}

关于c++ - Priority_queue 和输入流迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com