Domanda

Sto cercando di usare priority_queue e programma non riesce costantemente con CORRUZIONE messaggio di errore MUCCHIO RILEVATO.

qui ci sono i frammenti:

class CQueue { ...
              priority_queue<Message, deque<Message>, less<deque<Message>::value_type> > m_messages;
...};

classe Message è sovraccaricato operatori> e <

Qui mi riempio coda:

CQueue & operator+=(Message &rhv)
{
    m_messages.push(rhv);  //This is where program fails
    return *this;
}

e nel programma principale:

string str;
CQueue pq;
for(int i = 0; i < 12; ++i)
{
    cin >> str;

    Message p(str.c_str(), rand()%12); //Create message with random priority
    pq += p;                           //add it to queue
}

Non ho idea di quello che sembra essere il problema. Succede quando spingo circa 8 elementi, e non riesce on line

    push_heap(c.begin(), c.end(), comp);

in

: (

Questa è la definizione di classe di segnalazione - è molto semplice:

#pragma once 

#include <iostream>
#include <cstring>
#include <utility>

using namespace std;

 class Poruka
{
private:
char *m_tekst;
int  m_prioritet;
public:
Poruka():m_tekst(NULL), m_prioritet(-1){}

Poruka(const char* tekst, const int prioritet)
{
    if(NULL != tekst)
    {
    //  try{
            m_tekst = new char[strlen(tekst) + 1];
        //}
        //catch(bad_alloc&)
    //  {
    //      throw;
    //  }


        strcpy(m_tekst, tekst);
    }
    else
    { 
    //  try
    //  {
            m_tekst = new char[1];
    //  }
    //  catch(bad_alloc&)
    //  {
    //      throw;
    //  }

        m_tekst[0] = '\0';
    }
    m_prioritet = prioritet;
}

Poruka(const Poruka &p)
{
    if(p.m_tekst != NULL)
    {
        //try
        //{
            m_tekst = new char[strlen(p.m_tekst) + 1];
        //}
        //catch(bad_alloc&)
        //{
        //  throw;
        //}

        strcpy(m_tekst, p.m_tekst);
    }
    else
    {
        m_tekst = NULL;
    }
    m_prioritet = p.m_prioritet;
}

~Poruka()
{
        delete [] m_tekst;
}

Poruka& operator=(const Poruka& rhv)
{
    if(&rhv != this)
    {
        if(m_tekst != NULL)
            delete [] m_tekst;

    //  try
        //{
            m_tekst = new char[strlen(rhv.m_tekst + 1)];
        //}
        //catch(bad_alloc&)
        //{
        //  throw;
        //}

        strcpy(m_tekst, rhv.m_tekst);
        m_prioritet = rhv.m_prioritet;
    }
    return *this;
}

friend ostream& operator<<(ostream& it, const Poruka &p)
{
    it << '[' << p.m_tekst << ']' << p.m_prioritet;
    return it;
}

//Relacioni operatori

friend inline bool operator<(const Poruka& p1, const Poruka& p2)
{
    return p1.m_prioritet < p2.m_prioritet;
}

friend inline bool operator>(const Poruka& p1, const Poruka& p2)
{
    return p2 < p1;
}

friend inline bool operator>=(const Poruka& p1, const Poruka& p2)
{
    return !(p1 < p2);
}

friend inline bool operator<=(const Poruka& p1, const Poruka& p2)
{
    return !(p1 > p2);
}

friend inline bool operator==(const Poruka& p1, const Poruka& p2)
{
    return (!(p1 < p2) && !(p2 < p1));
}

friend inline bool operator!=(const Poruka& p1, const Poruka& p2)
{
    return (p1 < p2) || (p2 < p1);
}

};

Poruka - Messaggio

È stato utile?

Soluzione

Credo che il problema è che gli oggetti Message stanno mantenendo i puntatori alle stringhe prime C, che vengono poi sempre deallocata. In queste righe:

cin >> str;

Message p(str.c_str(), rand()%12);

In ogni iterazione del ciclo, che stai leggendo in un nuovo valore per str, che invalida qualsiasi vecchio puntatori restituiti dal suo metodo c_str(), in modo che i messaggi più vecchi stanno indicando i dati non validi. Si dovrebbe cambiare il vostro oggetto Message in modo che memorizza la sua stringa come std::string invece di un char*. Ciò correttamente copiare la stringa nell'oggetto Message.

In alternativa, se non è possibile cambiare la classe Message, dovrete copiare in modo esplicito la stringa da soli, per esempio utilizzando strdup() o malloc() / new[] + strcpy(), e poi si deve ricordarsi di rilasciare le copie della stringa in un momento successivo.

Altri suggerimenti

Non riesco a farlo sicuro.
Ma non c'è abbastanza informazioni per compilare questa linea:

push_heap(c.begin(), c.end(), comp);

Ma gli unici problemi che vedo sono:

1) Si dispone di un costruttore di default che potrebbe creare un Poruka con un nome NULL:

Poruka::Poruka():m_tekst(NULL), m_prioritet(-1){}

2) Non è un problema, perché si prova per esso la maggior parte dei posti, ma nel operatore di assegnazione si perde una prova:

Poruka::Poruka& operator=(const Poruka& rhv)
{
 ....
    // There was no test for 'rhv.m_tekst' being NULL here.
    //
    m_tekst = new char[strlen(rhv.m_tekst + 1)];
    strcpy(m_tekst, rhv.m_tekst);

Note:

  • Si potrebbe rendere il codice molto più semplice utilizzando la classe std :: string.
  • Se si desidera continuare a utilizzare char * poi se si gurantee non è mai NULL allora il codice è più semplice
  • Inoltre v'è un picchiettio più semplice per la definizione del costruttore di copia e l'assegnazione dell'operatore standard. Si riferisce a come la copia / idium swap.
  • Non avete bisogno di definire tutti quegli operatori relazionali. V'è una serie di quelle dei modelli che funzionano automaticamente a See http: //www.sgi. com / tecnologia / STL / operators.html . Hai solo bisogno di definire operatore

Ecco un esempio della copia / idium di swap

class X
{
     X(X const& copy)
     {
          // Do the work of copying the object
          m_tekst     = new char[strlen(copy.m_tekst) + 1];
          ...
          m_prioritet = copy.m_prioritet;
     }
     X& operator=(X const& copy)
     {
         // I like the explicit copy as it is easier to read
         // than the implicit copy used by some people (not mentioning names litb)
         //
         X  tmp(copy);  // Use the copy constructor to do the work

         swap(tmp);
     }
     void swap(X& rhs) throws ()
     {
         std::swap(this->m_tekst,   rhs.m_tekst);
         std::swap(this->prioritet, rhs.prioritet);
     }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top