grammar

#include <iostream>
#include <set>
#include <cstring>
#include <iterator>
#include <map>

using namespace std;

struct Production {
  char head;
  std::string body;
  bool operator < (const Production &a) const {
    return strcmp(&a.head, &head);
  }
};


class Grammar {
 public:
  Grammar() {}

  void set_production(std::multiset<Production> t) {
    production_ = t;
  }

  std::set<char> get_nonterminal() {
    for (std::set<Production>::const_iterator i = production_.begin(); i !=  production_.end(); i++)
      nonterminal_.insert((*i).head);

    return nonterminal_;
  }

  std::set<char> get_terminal() {
    if (nonterminal_.empty() == true)
      get_nonterminal();
    for (std::set<Production>::const_iterator i = production_.begin(); i !=  production_.end(); i++) {
      string t = (*i).body;
      for (std::string::const_iterator j = t.begin();
           j != t.end(); j++) {
        if (nonterminal_.find(*j) == nonterminal_.end())
          terminal_.insert(*j);
      }
        
    }
    return terminal_;
  }

 private:

  // private:
  std::set<char> nonterminal_;
  std::set<char> terminal_;
  std::multiset<Production> production_;
  std::map<char, char> table_;
  char start_;

};





template<typename T>
void DisplaySet(T s) {
  for (typename T::const_iterator i = s.begin(); i !=  s.end(); i++)
    // std::cout << (*i).head << "-->" << (*i).body << std::endl;
    std::cout << (*i) ;
}




int main()
{

 Production lst[] = {{'S', "aABb"},
                    {'A', "aAc"},
                    {'A', "&"}, //表示空
                    {'B', "bB"},
                    {'B',"c"}};

  std::multiset<Production> test(lst, lst+5);
  //  test.insert(&lst[0]);

  Grammar ll;
  ll.set_production(test);
  //  DisplaySet(ll.get_nonterminal());
  std::cout << std::endl;
  DisplaySet(ll.get_terminal());

  //  DisplaySet(ll.terminal_);
  //  std::cout << lst[0].head << " " << lst[0].body << std::endl;
}

你可能感兴趣的:(grammar)