开发者

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

How can I get the first five elements from开发者_开发问答 a queue without using for loop?


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: ;
}


#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;
}


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.

Anyway - if you means 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.

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.

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜