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
As pointed out by @ThorngardSO, the
reversedlistis 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:push_back()(inserts value at the end of the list)push_front()(inserts value at the beginning of the list)append()(Qt alternative forpush_back)prepend()(Qt alternative forpush_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:Also, note that there is a typo in your loop: it should be
++iinstead of++1.