2016-06-21 4 views
0

기본적으로이 논리 시뮬레이터는 작동하지 않습니다! 모든 게이트를 하나씩 연결하는 인접 목록을 만든 다음 머리글 인 AdjList에 값을 할당하면 함수 포인터를 사용하여 값을 계산해야합니다. 문제는 호출하는 유일한 기능입니다 그리고! (XOR 낸드 등 호출되지 않습니다) 특정 포인트 포인터가 함수 포인터가 구조체에서 그래프로 선언되어 동일한 함수를 할당했습니다.

struct AdjList 
{ 
    struct AdjListNode *head; 
    string GateName; 
    string OutputName; 
    bool result; 
    function <bool (vector <bool>)> ptrf; 

}; 

를 초기화하는 경우 그들이에 그런
 if(i < Gate_IO.size()) 
     { 
      ptrPos = Gate_IO[i].find_first_of(' '); 
      switch (strtoi ((Gate_IO[i].substr(0,ptrPos).c_str()))) 
      { 
       case strtoi("AND"): 
        { 
         VectorHeadPtr[i].ptrf = And; 
         break; 
        } 
       case strtoi("NAND"): 
        { 
         VectorHeadPtr[i].ptrf = Nand; 
         break; 
        } 
       case strtoi("OR"): 
        { 
         VectorHeadPtr[i].ptrf = Or; 
         break; 
        } 
       case strtoi("NOR"): 
        { 
         VectorHeadPtr[i].ptrf = Nor; 
         break; 
        } 
       case strtoi("XOR"): 
        { 
         VectorHeadPtr[i].ptrf = Xor; 
         break; 
        } 
       default: 
         break; 
      } 

을 할당했다 함수 CalcGateValue()는 프로그램을 실행하기 위해 호출됩니다! 그들이 인식되고 VectorHeadPtr [i] .ptrf의 올바른 값에 할당 된 것처럼 보입니다. 그 점에서 cout을 시도하고 해당 주기로 이동하지만 CalcGateValue()를 호출 할 때 호출되는 유일한 함수는 And입니다! 내가 놓친 게 있니? 난 당신의 코드는 당신이 그것을 생산하고 말을 생성하지 않습니다 생각

#include <iostream> 
#include <cstdlib> 
#include <string> 
#include <sstream> 
#include <vector> 
#include <algorithm> 
#include <functional> 
using namespace std; 
int compare(string a, string b) 
{ 
    int n = count(a.begin(), a.end(), 'I'); 
    int q = count(b.begin(), b.end(), 'I'); 
    return n > q; 
} 
constexpr unsigned int strtoi(const char* str, int h = 0) //string to int for switch cycle 
{ 
    return !str[h] ? 5381:(strtoi(str, h+1)*33)^str[h]; 
} 
     bool Xor(vector<bool> inputs) 
     { cout<<"Xor function called!"<<endl; 
      int counter = 0; 
      for (unsigned int i = 0;i < inputs.size(); i++) 
      { 
       if (inputs.at(i) == 1) 
       { 
        counter++; 
       } 
      } 
      if (counter % 2) //Xor gate gives output 1 if and odd number of 1 inputs is given 
      { 
       return 1; 
      } 
      else 
      { 
       return 0; 
      } 
     } 

     bool And(vector<bool> inputs) //static per richiamare la funzione dalla classe 
     { cout<<"And function called!"<<endl; 
      for (int i = 0; i < (inputs.size()-1); i++) 
       { 
        if(inputs.at(i) == 0) 
        { 
         return 0; 
        } 
       } 
      return 1; 
     } 
     bool Nand(vector<bool> inputs) 
     { cout<<"Nand function called!"<<endl; 
     return !And(inputs); 
     } 
     bool Or(vector<bool> inputs) 
     {cout<<"Or function called!"<<endl; 
      for (int i = 0; i < (inputs.size()-1); i++) 
      { 
       if (inputs.at(i) != inputs.at(i+1)) 
       { 
        return 1; 
       } 
      } 
      return inputs.at(0);//Any position it's ok because all nPoss are the same. 
     } 
     bool Nor(vector<bool> inputs) 
     { cout<<"Nor function called!"<<endl; 
      return !Or(inputs); 
     } 
/* 
* Adjacency list node 
*/ 
struct AdjListNode 
{ 
    int nPos; 
    bool gValue; 
    string name; 
    struct AdjListNode* next; 
}; 

/* 
* Adjacency list 
*/ 
struct AdjList 
{ 
    struct AdjListNode *head; 
    string GateName; 
    string OutputName; 
    bool result; 
    function <bool (vector <bool>)> ptrf; 

}; 

/** 
* Class Graph 
*/ 
class Graph 
{ 
    private: 
     int V; 
     int circInputs = 3; 
     int circOutputs = 2; 
     int circGates; 
     int PrimaryInputs = 0; 
     vector<string> ioPuts; 
     struct AdjList* VectorHeadPtr; 
    public: 
     Graph(vector<string> Gate_IO) 
     { 
      int ptrPos,cntr; 
      int cntrIO = 0; 
      int prevPrimaryInputs = 0; 
      bool flag_remove_duplicates = 0; 
      string GateToConnect; 
      circGates = Gate_IO.size(); 
      V=Gate_IO.size() + circInputs + circOutputs; //n°gates+input+output letti dal file 
      sort (Gate_IO.begin(), Gate_IO.end(), compare); 
      for (cntr = 0; cntr < (Gate_IO.size()-1) && (PrimaryInputs == prevPrimaryInputs); cntr++) 
      { 
       PrimaryInputs = count (Gate_IO[cntr+1].begin(), Gate_IO[cntr+1].end(), 'I'); 
       prevPrimaryInputs = count (Gate_IO[cntr].begin(), Gate_IO[cntr].end(), 'I'); 
      } 
      PrimaryInputs = cntr; //Here starts first N 
      for (int i = 0;i<Gate_IO.size();i++) 
      VectorHeadPtr = new AdjList [V]; 
      for (int i = 0; i < V; i++) 
      { 
       if(i < Gate_IO.size()) 
       { 
        ptrPos = Gate_IO[i].find_first_of(' '); 
        switch (strtoi ((Gate_IO[i].substr(0,ptrPos).c_str()))) 
        { 
         case strtoi("AND"): 
          { 
           VectorHeadPtr[i].ptrf = And; 
           break; 
          } 
         case strtoi("NAND"): 
          { 
           VectorHeadPtr[i].ptrf = Nand; 
           break; 
          } 
         case strtoi("OR"): 
          { 
           VectorHeadPtr[i].ptrf = Or; 
           break; 
          } 
         case strtoi("NOR"): 
          { 
           VectorHeadPtr[i].ptrf = Nor; 
           break; 
          } 
         case strtoi("XOR"): 
          { 
           VectorHeadPtr[i].ptrf = Xor; 
           break; 
          } 
         default: 
           break; 
        } 
        VectorHeadPtr[i].head = NULL; 
        stringstream ss; 
        ss << Gate_IO[i]; 
        for (string temp; ss >> temp;) 
        { 
         if ((temp.at(0)=='I') || (temp.at(0)=='O') && (temp!="OR")) 
         { 
          ioPuts.push_back(temp); 
         } 
         else if (temp.at(0) == 'U') 
         { 
          VectorHeadPtr[i].GateName=temp; 
         } 
        } 
        ptrPos = Gate_IO[i].find_last_of(' '); 
        VectorHeadPtr[i].OutputName = Gate_IO[i].substr(ptrPos); 
       } 
       else 
       { 
        if (flag_remove_duplicates == 0) 
         { 
          sort (ioPuts.begin(), ioPuts.end()); 
          ioPuts.erase (unique (ioPuts.begin(), ioPuts.end()), ioPuts.end()); 
          flag_remove_duplicates = 1; 
         } 
        VectorHeadPtr[i].head = NULL; 
        VectorHeadPtr[i].ptrf = NULL; 
        VectorHeadPtr[i].GateName = ioPuts[cntrIO]; 
        cntrIO++; 
       } 
      } 
      for (int i = 0; i < Gate_IO.size(); i++) 
      { 
       for(int j = 0; j < 2; j++) 
       { 
        ptrPos = Gate_IO[i].find_first_of(' ')+1; 
        Gate_IO[i].erase (0,ptrPos); 
       } 
       ptrPos = Gate_IO[i].find_last_of(' ')+1; 
       Gate_IO[i].erase(ptrPos); 
       stringstream ss; 
       ss << Gate_IO[i]; 
       ss >> GateToConnect; 
       for (string temp; ss >> temp;) 
       { 
        addEdge(GateToConnect,temp); 
       } 
      } 
     } 
     /** 
     * Creates new adjacency list node for addEdge function 
     */ 
     AdjListNode* newAdjListNode(int nPos, string Name) 
     { 
      AdjListNode* newNode = new AdjListNode; 
      newNode->nPos = nPos; 
      newNode->name = Name; 
      newNode->next = NULL; 
      return newNode; 
     } 
     /** 
     * Add edge to graph 
     */ 
     void addEdge(string source, string destination) 
     { 
      int from, to; 
      for (int i = 0; i < V; ++i) 
      { 
       if ((source == VectorHeadPtr[i].GateName) || (source == VectorHeadPtr[i].OutputName)) 
       { 
        from = i; 
       } 
       else if ((destination == VectorHeadPtr[i].GateName) || (destination == VectorHeadPtr[i].OutputName)) 
       { 
        to = i; 
       } 
      } 
      AdjListNode* newNode = newAdjListNode(to, destination); 
      newNode->next = VectorHeadPtr[from].head; 
      VectorHeadPtr[from].head = newNode; 
     } 
     /* 
     * Print the graph 
     */ 
     void printGraph() 
     { 
      for (int i = 0; i < circGates; i++)//meno ooutput+input 
      { 
       AdjListNode* Ptr = VectorHeadPtr[i].head; 
       cout<<endl<<"Gate connections for "<<VectorHeadPtr[i].GateName; 
       while (Ptr) 
       { 
        cout <<"-> "<< Ptr->name; 
        Ptr = Ptr->next; 
       } 
       cout<<" Output name is:"<<VectorHeadPtr[i].OutputName<<endl; 
      } 
     } 
     void calcGateVal() 
     { 
      vector<bool> Val={0, 1, 0}; 
      vector<bool> Op; 
      for (int i = 0; i < circOutputs; i++) 
      { 
       ioPuts.pop_back(); 
      } 
      for (int i = 0; i < circGates; i++) 
      { 
       AdjListNode* Ptr = VectorHeadPtr[i].head; 
       while (Ptr) 
       { 
        if (Ptr->name.at(0) == 'I') 
        { 
         for (int j = 0; j < ioPuts.size(); j++) 
         { 
          if (Ptr->name == ioPuts[j]) 
          { 
           Ptr->gValue = Val[j]; 
          } 
         } 
        } 
        Ptr = Ptr->next; 
       } 
      } 
      for (int i = 0; i < PrimaryInputs; i++) 
      { 
       AdjListNode* Ptr = VectorHeadPtr[i].head; 
       while (Ptr) 
       { 
        Op.push_back(Ptr->gValue); 
        Ptr = Ptr->next; 
       } 
       VectorHeadPtr[i].result = VectorHeadPtr[i].ptrf(Op); 
       cout<<"Gate Value is: "<<VectorHeadPtr[i].result<<" OutputName: "<<VectorHeadPtr[i].OutputName<<" GateName: "<<VectorHeadPtr[i].GateName<<endl; 
       Op.clear(); 
      } 
      for (int i = PrimaryInputs; i < V; i++) 
      { 
       AdjListNode* Ptr = VectorHeadPtr[i].head; 
       while (Ptr) 
       { 
         for (int j = 0; j < PrimaryInputs; j++) 
         { 
          if (Ptr->name == VectorHeadPtr[j].OutputName) 
          { 
           Ptr->gValue = VectorHeadPtr[j].result; 
          } 
         } 
        Ptr = Ptr->next; 
       } 
      } 
      for (int i = PrimaryInputs; i < circGates; i++) 
      { 
       AdjListNode* Ptr = VectorHeadPtr[i].head; 
       while (Ptr) 
       { 
        Op.push_back(Ptr->gValue); 
        Ptr = Ptr->next; 
       } 
       VectorHeadPtr[i].result = VectorHeadPtr->ptrf(Op); 
       Op.clear(); 
      } 
     } 
     void displayOutput() 
     { cout<<endl; 
      for (int i = 0; i < circGates; i++) 
      { 
       cout<<"Value of outputs are ("<<VectorHeadPtr[i].GateName<<") "<<VectorHeadPtr[i].OutputName<<": "<<VectorHeadPtr[i].result<<endl; 
      } 
     } 
}; 
/* 
* Main 
*/ 
int main() 
{ 
    vector<string> G_d; 
    G_d.push_back("AND 2 U0 I0 I1 N0"); 
    G_d.push_back("XOR 2 U1 N0 I2 O0"); 
    G_d.push_back("AND 2 U2 N0 I2 N1"); 
    G_d.push_back("AND 2 U3 I0 I1 N2"); 
    G_d.push_back("OR 2 U4 N1 N2 O1"); 
    Graph gh(G_d); 
    gh.calcGateVal(); 
    gh.displayOutput(); 
    gh.printGraph(); 

    // print the adjacency list representation of the above graph 

    return 0; 
} 

답변

0

: 다음은 전체 코드입니다. 여기를 참조하십시오 :

http://coliru.stacked-crooked.com/a/405b04c8d9113790 - Check the output of this

왜 문자열을 케이스 비교와 함께 strtoi로 정수로 변환 하시겠습니까? :

case strtoi("NAND"):

  • 더 나은 접근 방법을 strcmp 수 또는 문자열 과부하는 "=="동일한 동일한 비교를 아마도 룩업 테이블을 문자열의 각을 저장 할 것이다.

값 대신 참조로 벡터와 객체를 전달하는 것을 고려하면 객체에서 반환을 기대할 수 있지만 값을 전달하면 절대 보이지 않으므로이 객체의 복사본을 만드는 오버 헤드가 발생하지 않습니다. 벡터.

+0

둘러보기 주셔서 감사합니다! 결과를 더 잘 이해할 수 있도록 코드를 다시 업로드했습니다! 테이블에 훅 이라니? 내가 그 영역을 디버깅하려고 노력하고 그것은 잘 작동하는 것 같습니다! 나는 그것이 다른 일련의 것보다 더 이해할 수있는 것처럼 보이기 때문에 stroi를 사용했다. – Idan1109

+0

조회 테이블과 연결되지 않았다. 예 : std :: unordered_map ) >> lookuptable = {{ "AND", And}, { "NAND", Nand}}; - 일단이 방법을 선언하면 VectorHeadPtr [i] .ptrf = lookuptable [ "AND"]를 설정합니다.이 함수는 "AND"에 해당 함수를 제공합니다 –

+0

감사합니다. Samer Tufail 조회 테이블을 사용하면 쉽게 보입니다. 그것은 라인에서 작동 VectorHeadPtr [i] .ptrf = lookuptable [ "AND"]; 그것은 나를 준다 : – Idan1109

관련 문제