Question Regarding QVector Behavior
-
Hello,
I'm new to Qt and C++ in general. The following code is an attempt to copy files from a QVector. I need to remove the files from the QVector after they are copied, however, this causes the program to only copy around half the files. m_dirsToCopy is a QVector of directories the user selects, and m_selectedFilePaths05_01 is a QVector containing the files I am copying. The debug statement "vector size" shows that the vector contains half of the files when the program is over. Why is the program behaving this way? I'm pretty sure I am overlooking something basic here. Thanks in advance for any help you may provide.
void MainWindow::copyFiles05() { m_filesAreCopied01 = true; for(int i = 0; i < m_dirsToCopy05.size(); i++) { for(int j = 0; j < m_selectedFilePaths05_01.size(); j++) { QDir fromDir(m_dirsToCopy05.at(i)); if(! fromDir.isRoot() && i == 0) fromDir.cdUp(); QString filePath = m_dirsToCopy05.at(i); QString upFilePath = fromDir.absolutePath(); qDebug() << "upFilePath" << upFilePath; filePath = filePath.remove(upFilePath); qDebug() << "Filepath" << filePath; QString originalFile = m_selectedFilePaths05_01.at(j); originalFile = originalFile.remove(upFilePath); qDebug() << "altered path" << originalFile; QString newPath = m_destination05.at(0) + originalFile; qDebug() << "new path" << newPath; QDir newPath1(newPath); if(newPath1.exists()) emit fileToCopyIsPresentSignal05(newPath1.absolutePath()); if(! QFile::copy(m_selectedFilePaths05_01.at(j), newPath)) { QMessageBox::warning(this, "Error Copying File", "Error copying " + m_selectedFilePaths05_01.at(i) + "."); m_filesAreCopied01 = false; } if(m_filesAreCopied01) { m_numFilesCopied05 += 1; m_originalFiles05.append(m_selectedFilePaths05_01.at(j)); m_copiedFiles05.append(newPath1.absolutePath()); qDebug() << "vector size" << m_selectedFilePaths05_01.size(); //QVector <QString> copiedFiles; //copiedFiles.append(m_selectedFilePaths05_01.at(j)); //m_selectedFileNames05_01.shrink_to_fit(); emit progressBarUpdate05(m_numFilesCopied05); m_selectedFilePaths05_01.removeAt(j); } } }
-
@TheCRV said in Question Regarding QVector Behavior:
Why is the program behaving this way?
Because you're iterating until i or j < size(). But if you remove elements from the vector while you're iterating the size of the vector becomes smaller, right?
Why don't you simply empty the vector after you're done with copying? -
Simply iterate over the vector and add the ones which could not be copied to another vector which you can process later on.