Forward list and iterator

1

I'm looking at how to implement a list of objects in a class:

#include<iostream>
#include<forward_list>
#include <string>
using namespace std;



class Persona {
private:
    string m_nombre;
    int m_anios;
public:
    Persona() { m_nombre = ""; m_anios = 0; };
    ~Persona() {};
    string getNombre() { return m_nombre; };
    int getAnios() { return m_anios; };
    void setNombre(string nombre) { m_nombre = nombre; };
    void setAnios(int anios) { m_anios = anios; };
};

int main() {

    Persona p;
    p.setNombre("Juan");
    p.setAnios(20);

    forward_list<Persona> listaPersona;
    forward_list<Persona>::iterator it;

    it = listaPersona.begin();
    listaPersona.push_front(p);
    cout << it->getNombre();

    system("PAUSE");
    return 0;
}

What happens is that I do not really know how the iterator works and why the code does not work. I get an xstring exception "Read access violation _Right_data was 0x4"

    
asked by Chariot 18.10.2018 в 20:41
source

1 answer

2

You should get the iterator after to insert, if you do, it works correctly:

listaPersona.push_front(p);
it = listaPersona.begin();
cout << it->getNombre();

The iterator that you got before inserting, pointed to " nothing ", after inserting the begin , changed to something else. When you de-reference the iterator that pointed to " nothing ", you get the error at run time.

    
answered by 18.10.2018 / 21:34
source