c++求first和follow集代码
时间: 2023-04-21 11:06:56 浏览: 61
以下是C++代码实现First和Follow集合的算法:
First集合算法:
```
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
using namespace std;
map<string, set<string>> first;
void compute_first(string non_terminal, vector<vector<string>> productions) {
for (auto production : productions) {
if (production[0] == non_terminal) {
if (production[1] == "epsilon") {
first[non_terminal].insert("epsilon");
} else if (islower(production[1][0])) {
first[non_terminal].insert(production[1]);
} else {
compute_first(production[1], productions);
for (auto element : first[production[1]]) {
first[non_terminal].insert(element);
}
}
}
}
}
int main() {
vector<vector<string>> productions = {
{"S", "AB"},
{"A", "aA"},
{"A", "epsilon"},
{"B", "bB"},
{"B", "epsilon"}
};
for (auto production : productions) {
compute_first(production[0], productions);
}
for (auto element : first) {
cout << "First(" << element.first << ") = { ";
for (auto value : element.second) {
cout << value << " ";
}
cout << "}" << endl;
}
return 0;
}
```
Follow集合算法:
```
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
using namespace std;
map<string, set<string>> follow;
void compute_follow(string non_terminal, vector<vector<string>> productions) {
if (non_terminal == productions[0][0]) {
follow[non_terminal].insert("$");
}
for (auto production : productions) {
for (int i = 1; i < production.size(); i++) {
if (production[i] == non_terminal) {
if (i == production.size() - 1) {
compute_follow(production[0], productions);
for (auto element : follow[production[0]]) {
follow[non_terminal].insert(element);
}
} else {
if (islower(production[i + 1][0])) {
follow[non_terminal].insert(production[i + 1]);
} else {
compute_first(production[i + 1], productions);
for (auto element : first[production[i + 1]]) {
if (element != "epsilon") {
follow[non_terminal].insert(element);
} else {
compute_follow(production[0], productions);
for (auto element : follow[production[0]]) {
follow[non_terminal].insert(element);
}
}
}
}
}
}
}
}
}
int main() {
vector<vector<string>> productions = {
{"S", "AB"},
{"A", "aA"},
{"A", "epsilon"},
{"B", "bB"},
{"B", "epsilon"}
};
for (auto production : productions) {
compute_follow(production[0], productions);
}
for (auto element : follow) {
cout << "Follow(" << element.first << ") = { ";
for (auto value : element.second) {
cout << value << " ";
}
cout << "}" << endl;
}
return 0;
}
```