Skip to content

Instantly share code, notes, and snippets.

@abcsharp
Created October 22, 2011 07:17
Show Gist options
  • Save abcsharp/1305736 to your computer and use it in GitHub Desktop.
Save abcsharp/1305736 to your computer and use it in GitHub Desktop.
Brainfuckインタプリタ(ラムダ式+map使用版)
#include <iostream>
#include <map>
#include <functional>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
typedef std::pair<const char,std::function<void(void)>> Operator;
const int SourceLength=10000,MemorySize=30000;
char* Source;
unsigned char* Memory,* Ptr=0;
std::map<const char,std::function<void(void)>> Operators;
int Position;
int main(void)
{
Source=new char[SourceLength];
Memory=new unsigned char[MemorySize];
Operators.insert(Operator('>',[&](void){Ptr++;}));
Operators.insert(Operator('<',[&](void){Ptr--;}));
Operators.insert(Operator('+',[&](void){(*Ptr)++;}));
Operators.insert(Operator('-',[&](void){(*Ptr)--;}));
Operators.insert(Operator('.',[&](void){cout<<*Ptr;}));
Operators.insert(Operator(',',[&](void){*Ptr=cin.get();while(cin.get()!='\n');}));
Operators.insert(Operator('[',[&](void){if(!*Ptr) for(int n=1;++Position<SourceLength&&n;) Source[Position]=='['?n++:Source[Position]==']'?n--:n;}));
Operators.insert(Operator(']',[&](void){if(*Ptr) for(int n=1;--Position&&n;) Source[Position]=='['?n--:Source[Position]==']'?n++:n;}));
while(1){
for(int i=0;i<MemorySize;i++) Memory[i]=0;
Ptr=Memory;
Position=-1;
cout<<"Please input program.(Max length is "<<SourceLength<<")"<<endl<<">";
cin.getline(Source,SourceLength);
if(!strcmp(Source,"x")) break;
int Length=strlen(Source);
while(++Position<Length){
try{
Operators.at(Source[Position])();
}catch(...){
cout<<"Oh... \""<<Source[Position]<<"\" is an illegal character.";
break;
}
}
cout<<endl;
}
delete[] Source;
delete[] Memory;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment