2016-02-15 4 views
-2

main.cppКак использовать пользовательский класс в очереди приоритетов?

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <fstream> 
#include <algorithm> 
#include <iomanip> 
#include <sstream> 
#include <queue> 
#include<functional> 
#include "procedure.h" 

using namespace std; 


int gcounter = 0; 

//Comparator Classes 
struct ComparebyJobTime{ 
     bool operator()(Procedure lhs,Procedure rhs) { 
      return lhs.getTime() < rhs.getTime(); 
     } 
}; 

struct ComparebyProc{ 
     bool operator()(Procedure lhs, Procedure rhs){ 
      return lhs.getProc() < rhs.getProc(); 
     } 
}; 


typedef priority_queue<Procedure, vector<Procedure>, ComparebyProc> fcfs_q; 
typedef priority_queue<Procedure, vector<Procedure>, ComparebyJobTime> sjf_q; 

//Scheduling Algorithms 
void FCFS(fcfs_q procs, int n, int m, int t_cs){ 
    cout << "time " << gcounter << "ms: Simulator started for FCFS [Q "; 
    for(fcfs_q::iterator it = procs.begin(); it!= procs.end(), ++it{ 
     if(it == (procs.end() - 1){ 
      cout << *it.getProc() << "]" << endl; 
     } 
     else{ 
      cout << *it.getProc() << " "; 
     } 
    } 
} 

void SJF(sfj_q procs, int n, int m, int t_cs){ 
    cout << "time " << gcounter << "ms: Simulator started for SJF [Q "; 
    for(sjf_q::iterator it = procs.begin(); it != procs.end(); ++i{ 
     if(it == (procs.end() - 1){ 
      cout << *it.getProc() << "]" << endl; 
     } 
     else{ 
      cout << *it.getProc() << " "; 
     } 
    } 
} 

//Main function 
int main(int argc, char * argv[]) { 
    if (argc != 3){ 
     cerr << "Usage: " << argv[0] << "processes-file\n"; 
    } 
    ifstream in_file(argv[1]); 

    if(!in_file.good()){ 
     cerr << "Can not open the input file " << argv[1] << "\n"; 
    } 
    ofstream out_str(argv[2]); 
    if(!out_str){ 
     cerr << "Could not open " << argv[2] << "to write\n"; 
    } 

    string line; 
    fcfs_q pqf; 
    sjf_q pqs; 

    while(getline(in_file, line)){ 
     istringstream iss(line); 
     char com; 
     iss >> com; 
     if(line.length() == 0 || com == '#'){ 
      continue; 
     } 
     vector<string> split; 
     string token; 
     stringstream temp(line); 
     while(getline(temp, token, '|')){ 
      split.push_back(token); 
     } 
     pqf.push(Procedure(atoi(split[0].c_str()),atoi(split[1].c_str()),atoi(split[2].c_str()),atoi(split[3].c_str()))); 
     pqs.push(Procedure(atoi(split[0].c_str()),atoi(split[1].c_str()),atoi(split[2].c_str()),atoi(split[3].c_str()))); 
    } 
    //Simulation Start 
    int n = pqf.size(); 
    int m = 1; //Number of processors 
    int t_cs = 9; //Default context switch time 
    FCFS(pqf, n, m, t_cs); 
    cout << "time " << gcounter << "ms: Simulator ended for FCFS" << endl; 
    SJF(pqs, n, m, t_cs); 
    cout << "time " << gcounter << "ms: Simulator ended for SJF" << endl; 
} 

procedures.h

class Procedure{ 
    public: 
     Procedure(); 
     Procedure(int p, int bt, int num, int io){ 
      procNum = p; 
      burst = bt; 
      numBurst = num; 
      ioTime = io; 
     } 
     int getProc(){return procNum;} 
     int getNum(){return numBurst;} 
     int getIO(){return ioTime;} 
     int getTime(){return burst;} 

    private: 
     int procNum; 
     int numBurst; 
     int ioTime; 
     int burst; 
}; 

Ошибки:

hello-cpp-world.cc: In function ‘void FCFS(fcfs_q, int, int, int)’: 
hello-cpp-world.cc:39:9: error: ‘iterator’ is not a member of ‘fcfs_q {aka std::priority_queue<Procedure, std::vector<Procedure>, ComparebyProc>}’ 
    for(fcfs_q::iterator it = procs.begin(); it!= procs.end(), ++it{ 
     ^
hello-cpp-world.cc:39:26: error: expected ‘;’ before ‘it’ 
    for(fcfs_q::iterator it = procs.begin(); it!= procs.end(), ++it{ 
         ^
hello-cpp-world.cc:39:46: error: ‘it’ was not declared in this scope 
    for(fcfs_q::iterator it = procs.begin(); it!= procs.end(), ++it{ 
              ^
hello-cpp-world.cc:39:57: error: ‘fcfs_q’ has no member named ‘end’ 
    for(fcfs_q::iterator it = procs.begin(); it!= procs.end(), ++it{ 
                 ^
hello-cpp-world.cc:39:68: error: expected ‘;’ before ‘{’ token 
    for(fcfs_q::iterator it = procs.begin(); it!= procs.end(), ++it{ 
                    ^
hello-cpp-world.cc:39:68: error: expected primary-expression before ‘{’ token 
hello-cpp-world.cc:39:68: error: expected ‘)’ before ‘{’ token 
hello-cpp-world.cc:40:25: error: ‘fcfs_q’ has no member named ‘end’ 
     if(it == (procs.end() - 1){ 
         ^
hello-cpp-world.cc:40:35: error: expected ‘)’ before ‘{’ token 
     if(it == (procs.end() - 1){ 
           ^
hello-cpp-world.cc:46:5: error: expected primary-expression before ‘}’ token 
    } 
    ^
hello-cpp-world.cc:46:5: error: expected ‘;’ before ‘}’ token 
hello-cpp-world.cc: At global scope: 
hello-cpp-world.cc:49:10: error: variable or field ‘SJF’ declared void 
void SJF(sfj_q procs, int n, int m, int t_cs){ 
     ^
hello-cpp-world.cc:49:10: error: ‘sfj_q’ was not declared in this scope 
hello-cpp-world.cc:49:23: error: expected primary-expression before ‘int’ 
void SJF(sfj_q procs, int n, int m, int t_cs){ 
        ^
hello-cpp-world.cc:49:30: error: expected primary-expression before ‘int’ 
void SJF(sfj_q procs, int n, int m, int t_cs){ 
          ^
hello-cpp-world.cc:49:37: error: expected primary-expression before ‘int’ 
void SJF(sfj_q procs, int n, int m, int t_cs){ 
            ^

С этим выше блока кода и определенного файла procedure.h, я получаю сообщение об ошибке, говоря что мой итератор typedef не является допустимым классом. Я не могу понять, что вызывает это, может ли кто-нибудь увидеть ошибки в моем коде выше?

+1

При размещении вопросов о ошибке сборки, пожалуйста, включите фактический, полный, полный и неотредактированный вывод ошибки в орган вопроса, включая любые информационные заметки. –

+1

Это та же проблема, что и приоритетная очередь, например, 'int'. Ничего общего с вашим собственным типом. Проконсультируйтесь с [ссылкой] (http://en.cppreference.com/w/cpp/container/priority_queue) для доступных операций. – chris

+0

Я обновил его @JoachimPileborg – Nick

ответ

0

Ни std:queue, ни std::priority_queue не повторяются, поэтому типы и методы, которые вы пытаетесь вызвать, не определены. Вы можете эмулировать итерацию в очереди, как показано ниже, но будьте осторожны: эта операция уничтожит очередь. Поскольку вы передаете объект очереди по значению, а не по ссылке, оригинал не будет уничтожен, а только копия, но само копирование может занять некоторое время.

void FCFS(fcfs_q procs, int n, int m, int t_cs){ 
    cout << "time " << gcounter << "ms: Simulator started for FCFS [Q "; 
    while (!fcfs.empty()) { 
     const auto& elem = fcfs.top(); 
     if(fcfs.size() == 1){ // the last element in the queue 
      cout << elem.getProc() << "]" << endl; 
     } 
     else{ 
      cout << elem.getProc() << " "; 
     } 
     fcfs.pop(); 
    } 
} 

См How to iterate over a priority_queue? и STL queue iteration для дальнейшего чтения.

Кроме того, возможно, заглянуть в алгоритмах кучи STL, таких как make_heap(), push_heap(), pop_heap() и sort_heap() в <algorithm>. Это позволяет вам явно хранить элементы в контейнере по вашему выбору, сохраняя все свои свойства, например, способность перебирать его, сохраняя при этом сортировку.