Please, explain the code

The main body is especially unclear.
https://pastebin.com/aSANRsEL
A file contains the state of a machine for interpreting instructions, and some instructions.

The start of the file is read and used to put the machine object into the right state.

The rest of the file is instructions that are read and executed by the machine.
Could You explain, please, this part?

std::ifstream ifs(filename, std::ifstream::in);
machine m;
ifs >> m;
std::vector<instruction> program;
std::copy(std::istream_iterator<instruction>(ifs),
std::istream_iterator<instruction>(),
std::back_inserter(program));
for(std::size_t i = 0; !m.end_of_tape() && i < program.size();) {
if(m.execute(program[i])) i = 0;
else i++;
std::cout << m.tape << std::endl;
Last edited on
td::ifstream ifs(filename, std::ifstream::in);
Open file.

machine m;
Create machine object.

ifs >> m;
Load state of machine from file

std::vector<instruction> program;
Create vector to hold the instructions

1
2
3
std::copy(std::istream_iterator<instruction>(ifs),
std::istream_iterator<instruction>(),
std::back_inserter(program));

Load instructions from file.

Then machine executes instructions.
And this one if You don't mind:
std::istream & operator>>(std::istream &is, machine &m) {
m.state = "0";
is >> m.position; m.position--;
return is >> m.tape;
std::istream & operator>>(std::istream &is, machine &m)
Function takes an istream ref and a machine ref as input parameters, and returns a ref to an istream

m.state = "0";
Take a guess

is >> m.position;
Read in value from stream. Store it in m.position

m.position--;
Take a guess

is >> m.tape;
Read in value from stream. Store it in m.tape
Last edited on
Thank You.
Topic archived. No new replies allowed.