Mrchacha Mrchacha - 1 year ago 84
C++ Question

Get the previous element of a QStringList

I'm currently working on a small program where I will count the amount of times a certain word is mentioned in a text. But I only want to count for the word when the previous element is a 10 digit number.
So what I'm trying is do is that I will check if the previous element of the iterator consist of a 10 digit number. But I don't know how to iterate to the previous element from the iterator.

QString input = ui->listinput->toPlainText();

QStringList inputlist = input.split(QRegExp("[\s\n\r " "]+"));

unsigned int boxCount(0);

for(QStringList::iterator it(inputlist.begin()); it != inputlist.end(); ++it){

if(!QString::compare(*it,box)) ++boxCount;


So I want the if statement to be something like this:

if(!QString::compare(*it,box) && *prev_it == 10 digits) ++boxCount;

Any help will be appreciated. Thanks!

Answer Source

You can obtain the previous iterator by doing:

if (it != inputlist.begin()) {
    prev_it = it - 1

You will have to make an exception for the first element, since it has no previous element. Either check the range (like above) or start your for loop one element past the first (note the '+ 1'):

for (QStringList::iterator it(inputlist.begin() + 1); it != inputlist.end(); ++it) {

In the latter case, you must be sure that your list contains at least one element.

If you then want to check if the number is 10-digit (assuming decimal and integer) you can try the following:

bool ok = false;
long num = prev_it->toLong(&ok);
if (ok && num >= 1000000000) {
    // do something

Note: I used the long type because I do not know the range of your numbers, but they seemed big.