简体   繁体   English

通过地图C ++反向进行STL循环

[英]STL looping in reverse through map C++

const map<player, int>::iterator beginning = game->begin(); 
const map<player, int>::iterator inserted = game->find(player(x, y));
map<player, int>::iterator left = inserted;
while(left != beginning)
{
//some operations here
--left;
}

As you, see I want to loop through the map in reverse, accessing all the elements before the one i've just inserted. 如您所见,请参阅我想反向遍历地图,在我刚刚插入的元素之前访问所有元素。 The problem is, with the construction above it doesn't access the first element and I have no idea why. 问题是,上面的构造无法访问第一个元素,我也不知道为什么。 Any suggeestions? 有什么建议吗? Is game->begin() the first element? game-> begin()是第一个元素吗? If so, how to solve it? 如果是这样,如何解决呢?

You can use rbegin() and rend() . 您可以使用rbegin()rend()

See here http://www.cplusplus.com/reference/map/map/rbegin/ . 参见http://www.cplusplus.com/reference/map/map/rbegin/

game.begin() is iterator to the first element. game.begin()是第一个元素的迭代器。

you can start from the end of map by assigning the iterator to rbegin 您可以通过将迭代器分配给rbegin从地图的末尾开始

map<player, int>::reverse_iterator it = game.rbegin()

for (it = game.rbegin(); it != game.rend(); it++)
{
}

The following will access all the elements before the one just inserted (not including the one just inserted). 以下内容将访问刚插入的元素之前的所有元素(不包括刚插入的元素)。 It also protects against the situation where there are no elements 'before' the inserted element: 它还可以防止插入的元素“之前”没有元素的情况:

if (left != beginning) { 
    do {
        --left;
        //some operations here
    } while (left != beginning);
}

The condition in the loop is wrong. 循环中的条件是错误的。 You are asking to skip the loop when the iterator is begin , but you actually want to execute it in that case. 您要求在迭代器begin时跳过循环,但实际上您希望在这种情况下执行该循环。

There are different things that you can do, the one that will cause the lesser impact in your code is probably going to be changing the loop to be infinite and adding the exit condition before changing the iterator: 您可以执行不同的操作,这将对代码产生较小的影响,这可能是将循环更改为无限,并在更改迭代器之前添加退出条件:

while (true) {
   // do something
   if (it == begin()) break;
   --it;
}

Alternatively you can use reverse iterators (which you can initialize with your current iterator) and test against rend() . 或者,您可以使用反向迭代器(可以使用当前的迭代器进行初始化),并针对rend()测试。

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

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