Reputation: 167
In my Qt C++ application I have a QList I want to increase the contents of each index by the same amount!
void MainWindow::on_pushButton_clicked()
{
list1<<"a"<<"b"<<"c"<<"d"<<"e";
list2<<"f"<<"g"<<"h"<<"i"<<"j";
List1<<list1;
List2<<list2;
for(int k=0;k<2;k++){
for(int i=0;i<List1.size();i++){
for(int j=0;j<List1[0].size();j++){
List1[i]<<List1[i][j];
}
}
}
}
from the above code I want to make the contents of 0th index of List (i.e List[0]) a QStringList of "a" "b" "c" "d" "e" "a" "b" "c" "d" "e" and the contents of 1st index of List (i.e List[1]) a QStringList of "f" "g" "h" "i" "j" "f" "g" "h" "i" "j"! But when I click the button I get the run time error stating
terminate called after throwing an instance of 'std::bad_alloc'
How can I correct this?
Upvotes: 0
Views: 580
Reputation: 6329
In case you have problems with code, try to make it work as a complete sample, like this:
void test()
{
QList<QStringList> ListOfLists;
ListOfLists.append(QStringList());
ListOfLists.append(QStringList());
ListOfLists[0] << "a" << "b";
ListOfLists[1] << "g" << "f";
qDebug() << ListOfLists; // (("a", "b"), ("g", "f"))
for (int i=0; i<ListOfLists.size(); ++i)
{
QStringList tempList = ListOfLists[i];
foreach(QString s, tempList)
{
ListOfLists[i] << s;
}
}
qDebug() << ListOfLists; // (("a", "b", "a", "b"), ("g", "f", "g", "f"))
}
Usually, problems disappear, once you rewrite your code in clean way. Your code has two Lists, List1 and List2 and some array, where nobody can track what goes wrong. I quess, that your code recurses over the list until memory is exhausted. That's why I make a copy called tempList to avoid infinite recursion.
Upvotes: 1