The iterator should have different behavior when calling next () / previous () for elements

I created a simple map and an iterator on it. When I transfer the iterator to the following elements, it works well. After redirecting the iterator, if I ask him to return to the previous element and get the value () of the iterator, this is not really the previous value of the element, and in fact the value does not change at all. Something seems to be wrong, or maybe I'm using it the wrong way! Where is the problem?

see below code

#include "mainwindow.h"
#include <QApplication>
#include <QMap>
#include <qiterator.h>

int main(int argc, char *argv[])

{
    QApplication a(argc, argv);

QMap<double,int> map;
map.insert(4234,3);
map.insert(4200,2);
map.insert(4100,1);
map.insert(4000,0);

QMapIterator<double, int> i(map);
i.toFront();

i.next();
i.next();
int va1 = i.value();    // val1 is 1 as expected

i.previous();

int val2 = i.value(); // It is expected that val2 should be 0 but is still Surprisingly 1!!!!

return a.exec();
}
+4
source share
1 answer

This is for the design and behavior of Java style iterators. Iterators have two important states associated with them:

  • Position.
  • Direction

, .

next() previous() . next(), . previous() .

. - . v .

i.toFront();
-v
  4000 4100 4200 4234
  0    1    2    3

i.next();
  ----v
  4000 4100 4200 4234
  0    1    2    3

i.next();
       ----v
  4000 4100 4200 4234
  0    1    2    3

i.previous();
      v----
  4000 4100 4200 4234
  0    1    2    3

i.previous();
 v----
  4000 4100 4200 4234
  0    1    2    3

:

#include <QtCore>
int main()
{
   QMap<double, int> map;
   map.insert(4234., 3);
   map.insert(4200., 2);
   map.insert(4100., 1);
   map.insert(4000., 0);

   QMapIterator<double, int> i(map);
   i.toFront();

   i.next();
   qDebug() << i.key() << i.value();
   i.next();
   qDebug() << i.key() << i.value();

   i.previous();
   qDebug() << i.key() << i.value();
   i.previous();
   qDebug() << i.key() << i.value();
}

:

4000 0
4100 1
4100 1
4000 0

, , ++ .

+1

Source: https://habr.com/ru/post/1658094/


All Articles