Problems to remove vector node

Asked

Viewed 68 times

4

I have two classes:

class CAlbum
{
private:
    QString Nome; /**< Nome do Álbum */
    QString Descricao; /**< Descrição do Álbum */
    QString Diretoria; /**< Diretoria onde se encontra o Álbum */
    //QPixmap Imagem;
    std::vector <CInterprete> Interpretes; /**< Informação relativa aos Intérpretes associados ao Álbum */
    std::vector <CMusica> Musicas; /**< Músicas presentes no Álbum */
public: ...
}

class CInterprete
{
    QString Nome; /**< Nome do Intérprete */
    QString Nacionalidade; /**< Nacionalidade do Intérprete */
    QDate Nascimento; /**< Data de Nascimento do Intérprete */

public: ...
}

And one of the operators I have in class CAlbum is as follows:

bool CAlbum::elimina_Interprete(const QString nome_Interprete){
    int i;
    for ( i = 0 ; i < (int) Interpretes.size() ; i++){
        if (Interpretes[i].retorna_Nome() == nome_Interprete){
            Interpretes.erase(Interpretes.begin()+i);
            return true;
        }
    }
    return false;
}

I’ve tried applying the same idea but with Iterators and it didn’t work, always giving me a mistake

Debug Assertion Failed! Expression: vector Erase iterator Outside range"

How is it that with this function I find myself eliminating outside the crease?

1 answer

3


Since you’re using Qt why didn’t you use the QVector? This can solve the problem, or at least become more standardized and can improve performance. On the other hand, if you’re going to use STL, then use all of it and forget about Qt structures.

I can’t exactly test this code because it doesn’t have everything I’d need to test, but I ran a test with the same algorithm and it all worked out.

#include <vector>
#include <iostream>

using namespace std;
int main() {
    vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    for (auto &i : v) cout << i << " ";
    cout << '\n';
    for (int k = 0; k <= 10; k++) {
        for (int i = 0; i < v.size(); i++) {
            if (v[i] == k) {
                v.erase(v.begin() + i);
                break;
            }
        }
    }
    for (auto &i : v) cout << i << " ";
    cout << '\n';
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you for your time. The problem is right on this piece of code. I had checked earlier through qDebug(). Regarding Qvector I didn’t even know it :) It’s the first time I’m working with vectors. I’ll make that change ;) Thank you.

  • Qvector solved the problem!! Thanks for the help ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.