简体   繁体   English

如何从队列中获取前5个元素C ++

[英]How to get the first 5 elements from a queue c++

如何在不使用for循环的情况下从队列中获取前五个元素?

No explicit loops at all: 根本没有显式循环:

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>

template <typename T>
class QueuePopper
{
public:
    QueuePopper(std::queue<T> &q) : q(q) {}
    T operator() (const T &) { T t = q.front(); q.pop(); return t; }
private:
    std::queue<T> &q;
};

int main()
{
    typedef std::string T;

    std::queue<T> q;

    ...

    std::vector<T> v(5);
    std::transform(v.begin(), v.end(), v.begin(), QueuePopper<T>(q));
}

One more way: 另一种方式:

template<int n> void GetElements(queue<string>& qu)
{
    if(!qu.empty())
    {
        cout << qu.front() << '\n';
        qu.pop();
    }
    GetElements<n-1>(qu);
}

template<> void GetElements<0>(queue<string>& qu) {}

// and call:
GetElements<5>(qu);

Or: 要么:

switch(qu.size())
{
default: cout << qu.front() << '\n'; qu.pop();
case 4: cout << qu.front() << '\n'; qu.pop();
case 3: cout << qu.front() << '\n'; qu.pop();
case 2: cout << qu.front() << '\n'; qu.pop();
case 1: cout << qu.front() << '\n'; qu.pop();
case 0: ;
}

Why would you want to do that? 你为什么想这么做? Maybe you have to hold 5 elements in hand at a time fr reasons that are not clear here. 也许您一次必须拥有5个元素,而原因在这里还不清楚。

Anyway - if you means STL <queue> : 无论如何-如果您表示STL <queue>

std::queue<Element> container;

Element e1, e2, e3, e3, e5;

e1 = container.front();
container.pop();
e2 = container.front();
container.pop();
e3 = container.front();
container.pop();
e4 = container.front();
container.pop();
e5 = container.front();
container.pop();

Behaviour is undefined if < 5 elements on the queue . 如果queue元素少于5个,则行为是不确定的。

You can replace this with the below if you want to avoid the Element copy, however in this case be aware that the reference becomes invalid after the referenced element is popped. 如果要避免Element复制,可以将其替换为以下内容,但是在这种情况下,请注意,在弹出引用的元素后,引用将变为无效。

std::queue<Element> container;

Element& e1 = container.front();    // or const Element&
container.pop();
Element& e2 = container.front();
container.pop();
Element& e3 = container.front();
container.pop();
Element& e4 = container.front();
container.pop();
Element& e5 = container.front();
container.pop();
#include <iostream>
#include <queue>

int main(){
    std::queue<std::string> q;
    for (int i = 0; i<5; ++i){
        std::string s;
        std::cin >> s;
        q.push(s);
    }
    int itemsToFetch = 5;
    do{
        std::string curString = q.front();
        q.pop();
        std::cout << curString << std::endl;
        --itemsToFetch;
    } while (itemsToFetch > 0 && !q.empty());
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM