Skip to content

Instantly share code, notes, and snippets.

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