C ++ Vector Front - PullRequest
       50

C ++ Vector Front

0 голосов
/ 09 октября 2011

У меня проблемы с функциями getFirst (), они должны возвращать первый элемент deque / vector, но вместо этого они возвращают фиксированные значения, такие как 45 или 69!

Например: IДобавить (0xFB) ... затем попробовать printf ("% d", p_MsgQueue-> getFirst ()) Вывод: 69 ????

MessageQueue.h

/*
 * Copyright (C) 2011 - 2012 Project Avalance
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#ifndef MESSAGEQUEUE_H
#define MESSAGEQUEUE_H

#define MQ_USE_DEQUE

#ifdef MQ_USE_VECTOR
#include <vector>
/* THIS VECTOR WILL BE USED BY MESSAGE_QUEUE TO STORE THE-TO BE PROCCESSED MESSAGES (SLASH) SIGNALS.*/
typedef std::vector<int> MESSAGE_LIST; // SHARED OBJECT .. MUST LOCK!

/* THIS CLASS WILL HANDLE THE MESSAGE LIST.*/
class MESSAGE_QUEUE {
public:
    MESSAGE_LIST * m_pList; // Pointer to our list, it's better to leave MESSAGE_LIST outside this class.
    MESSAGE_QUEUE(MESSAGE_LIST* pList){ m_pList = pList; } // POINTER TO OUR LIST HANDLER = POINTER TO THE LIST CREATED BY THE CALLING SCOPE MESSAGE_QUEUE (&AddressOfList)
    ~MESSAGE_QUEUE(){ } // Destructor , this will destroy m_pList when the class gets out of scope (todo)
    /* This class will be shared between threads that means any attempt to access it MUST be inside a critical section. */
    void Add( int messageCode ){ if(m_pList && messageCode!=0xFF)m_pList->push_back(messageCode);  } // Adding a message; Added check if input is 0xFF.
    int getLast( ){ if(m_pList){ return m_pList->back(); } return -1; } // MUST BE IN THE CODE : if(m_pList->size() == 0){ add(0xFF); } -- 0xFF CODE IS RESERVED! DO - NOT - USE
    void removeLast( ){ if(m_pList && m_pList->size() > 0){ m_pList->erase(m_pList->end()-1,m_pList->end()); } } // Deleting the last message , idk about iters+1 efficiency, there might be other ways to do it like advance(const_iterator,int)
    void removeFirst( ){ if(m_pList && m_pList->size() > 0){ m_pList->erase(m_pList->begin()); } }
    int getFirst( ){ if(m_pList){ return m_pList->front(); } return -1; }
};
#endif

#ifdef MQ_USE_DEQUE
#include <deque>
/* THIS VECTOR WILL BE USED BY MESSAGE_QUEUE TO STORE THE-TO BE PROCCESSED MESSAGES (SLASH) SIGNALS.*/
typedef std::deque<int> MESSAGE_LIST; // SHARED OBJECT .. MUST LOCK!

/* THIS CLASS WILL HANDLE THE MESSAGE LIST.*/
class MESSAGE_QUEUE {
public:
    MESSAGE_LIST * m_pList; // Pointer to our list, it's better to leave MESSAGE_LIST outside this class.
    MESSAGE_QUEUE(MESSAGE_LIST* pList){ m_pList = pList; } // POINTER TO OUR LIST HANDLER = POINTER TO THE LIST CREATED BY THE CALLING SCOPE MESSAGE_QUEUE (&AddressOfList)
    ~MESSAGE_QUEUE(){ } // Destructor , this will destroy m_pList when the class gets out of scope (todo)
    /* This class will be shared between threads that means any attempt to access it MUST be inside a critical section. */
    void Add( int messageCode ){ if(m_pList && messageCode!=0xFF)m_pList->push_back(messageCode);  } // Adding a message; Added check if input is 0xFF.
    int getLast( ){ if(m_pList){ return m_pList->back(); } return -1;} // MUST BE IN THE CODE : if(m_pList->size() == 0){ add(0xFF); } -- 0xFF CODE IS RESERVED! DO - NOT - USE
    void removeLast( ){ if(m_pList && m_pList->size() > 0){ m_pList->erase(m_pList->end()-1,m_pList->end()); } } // Deleting the last message , idk about iters+1 efficiency, there might be other ways to do it like advance(const_iterator,int)
    void removeFirst( ){ if(m_pList && m_pList->size() > 0){ m_pList->erase(m_pList->begin()); } }
    int getFirst( ){ if(m_pList){ return m_pList->front(); } return -1;}
};
#endif

#endif

Где-нибудьв Command.h

            ArgParser arg;
            int value = arg.GetHexArgs(_input,strlen("message -add 0x"));
            if(value == -1)CLog->out("\n Bad Arguement!");
            if(value != -1)CLog->out("\n 0x%X",value);
            LockSection Lc(Cs,errHandler);
            msgQueue->Add(value);
            printf(" %d ",msgQueue->getFirst());
            Lc.ForceCSectionLeave();

Main.cpp

LockSection lc(&crt,&err);
CLog->out(" [ Adding message = 0x45 ] Action : None \n");
g_msgQueue.Add(0x45);
CLog->out(" [ Adding message = 0xFD ] Action : Stalling Backgrounder Thread...\n");
g_msgQueue.Add(0xFD);
lc.ForceCSectionLeave();

/* Initialize Manager/Threads */
Backgrounder backgrounder;
if(backgrounder.Begin(&g_msgQueue,&crt,&err) == -1){ CLog->out(" - Initializing Backgrounder Sevice (backgrounder)  ... Failed!\n [Warning]! An error occured while initializing Backgrounder Sevice (backgrounder)."); }

CommandManager Cmd_Mgr;
if(Cmd_Mgr.Begin(&g_msgQueue,&crt,&err) == -1){ CLog->out(" - Initializing Command Manager Service (Cmd_Mgr)  ... Failed!\n [Warning]! An error occured while initializing Command Manager Service (Cmd_Mgr)."); }

while(g_msgQueue.getLast() != 0xFF){ 
    if(g_msgQueue.getLast() == 0xFE){
        CLog->out("\n == WARNING == SERVICE RESTART MESSAGE WAS RECIEVED .... REBOOTING ALL SECONDARY THREADS! "); // Todo, _endthread // and nicely reboot

    }
}
return 0;

Оказывается, я добавлял значения в другой файл.Обратите внимание:

LockSection lc(&crt,&err);
CLog->out(" [ Adding message = 0x45 ] Action : None \n");
g_msgQueue.Add(0x45);
CLog->out(" [ Adding message = 0xFD ] Action : Stalling Backgrounder Thread...\n");
g_msgQueue.Add(0xFD);
lc.ForceCSectionLeave();

1 Ответ

1 голос
/ 09 октября 2011
  • функция Add () всегда будет распечатывать первый добавленный элемент: если вы рекламируете 69, 45, 89, 34, она всегда будет печатать 69, который является первым добавленным элементом

  • Вам не нужно наследовать от MESSAGE_LIST (вектор или очередь), вы просто используете их в члене m_pList

  • , если m_pList равен нулю, ваша программа будетсбой, потому что вы не возвращаете никакого значения, когда должны

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...