简体   繁体   中英

How to print a deque from the end?

Question is quite simple, how do I print a deque, but from behind. Example: I have a deque with elements {5,4,3,2,1}. I want to print that deque, but starting from the last element, so I should have someting like 1 2 3 4 5 on my screen.

Usual for(int i(deque.size()); i > 0; i--) loop obviously won't work. Little intro to the program. It finds numbers whose sum is even or odd, and sorts them into two different deques that are to be printed on screen. This is the code that works for 'usual' printing. But my task says to print them backwards. Oh, and the elements are added to the deque using push_front function. And no, I'm not allowed to use push_back to 'fix' it.

void PrintDek(Dek v4) {
for (int i(0); i < v4.size(); i++) {
    std::cout << v4[i];
    if (i != v4.size() - 1) std::cout << ",";
}
}

If some of you feel the need for the whole program's code, I'll edit my post.

You can use reverse iterators . See http://en.cppreference.com/w/cpp/container/deque/rbegin .

for(auto iter = deque.rbegin(); iter != deque.rend(); ++iter) {
    // do stuff
}

So after seeing my code after a good few hours of sleep (this question was posted after 2AM according to my timezone), I've come to realize what my mistake was. By using deque.size() and moving all the way up to the value that the size() function returns, I was actually going out of range, accessing forbidden parts of memory. Simple deque.size()-1 now works. So the loop would look like this for(int i(deque.size()-1); i >= 0; i--) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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