QStringList "index out of range"

2k Views Asked by At

I am trying to reverse the words within a QStringList. Below is the code up to now, but I keep on getting a "Index out of Range" error. From the error it would seem that I am trying to use data that is out of scope, but not able to figure out my problem.

QString reversed;
QStringList reversedlist;
QStringlist list = input.split(" ");

for (int i=0;i<list.length(); ++1)
  reversedlist[i] = list[list.length() -1 -i];

reversed = reversedlist.join(" ");`

Thanks

3

There are 3 best solutions below

6
On

As pointed out by @ThorngardSO, the reversedlist is initially empty, and you are trying to access the invalid index in your loop code. You should add values to the list using one of the following functions:

  • STL-compatible function push_back() (inserts value at the end of the list)
  • STL-compatible function push_front() (inserts value at the beginning of the list)
  • Qt function append() (Qt alternative for push_back)
  • Qt function prepend() (Qt alternative for push_front)

As you see, prepend() inserts the element at the beginning of the list, that is why it makes the reversing of the list very simple:

for (int i = 0; i < list.length(); ++i) {
    reversedlist.prepend(list[i]);
}

Also, note that there is a typo in your loop: it should be ++i instead of ++1.

0
On

Your reversedList is initially empty. You have to actually append the items, like this:

reversedlist.push_back (list[list.length () - 1 - i]);

Naturally, trying to access non-existing items via reversedList[i] does not work and throws the index-out-out-range error.

0
On

You got the index out of range as there is no sting inside the QStringList reversedlist. So when your code reach the line reversedlist[0], it throw the "index out of range" error. And you can read the value using [0] and cant assign. if you want to assign the value to a particular index of the QStringList.

QString reversed;
    QStringList reversedlist;

    QString input="123 456 789 000";
    QStringList list = input.split(" ");

    for (int i=0;i<list.length(); ++i){
      //value to particular index
      reversedlist.insert(i,list[list.length() -1 -i]);
    }

    reversed = reversedlist.join(" ");

    qDebug() << reversed;