循环中删除list元素

1、程序崩溃,mylist越界。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList<int> mylist;
    for(int i=0;i<10;i++)
    {
        mylist.append(i);
    }

    for(int i=0;i<10;i++)
    {
        mylist.at(i);//程序崩溃
        if(i == 3)
        {
            mylist.removeAt(i);
        }
    }
    qDebug() << mylist;
}

MainWindow::~MainWindow()
{
    delete ui;
}

2、可以用foreach循环。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include 
#include 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList<int> mylist;
    for(int i=0;i<10;i++)
    {
        mylist.append(i);
    }

    foreach(auto item,mylist)
    {
        if(item == 3)
        {
           mylist.removeOne(item);
        }
    }
    qDebug() << mylist;
}

MainWindow::~MainWindow()
{
    delete ui;
}

3、qt中foreach实现源码如下

#if defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && !defined(Q_CC_RVCT)
/* make use of typeof-extension */
template <typename T>
class QForeachContainer {
public:
    inline QForeachContainer(const T& t) : c(t), brk(0), i(c.begin()), e(c.end()) { }
    const T c;
    int brk;
    typename T::const_iterator i, e;
};

#define Q_FOREACH(variable, container)                                \
for (QForeachContainer<__typeof__(container)> _container_(container); \
     !_container_.brk && _container_.i != _container_.e;              \
     __extension__  ({ ++_container_.brk; ++_container_.i; }))                       \
    for (variable = *_container_.i;; __extension__ ({--_container_.brk; break;}))

#else

你可能感兴趣的:(QT)