Skip to content

Instantly share code, notes, and snippets.

@slwu89
Created April 30, 2018 17:58
Show Gist options
  • Save slwu89/336705da37386a1bdfb60d3534a07436 to your computer and use it in GitHub Desktop.
Save slwu89/336705da37386a1bdfb60d3534a07436 to your computer and use it in GitHub Desktop.
example of using std::map to store string keys and values that are bound member functions with 1 parameters
#ifndef human_hpp
#define human_hpp
#include <stdio.h>
#include <iostream>
#include <string>
#include <random>
#include <functional>
#include <map>
using namespace std::placeholders;
class human {
public:
human(const std::string& _state, int _id) : id(_id), state(_state) {
std::cout << "human: " << id << " state: " << state << " being born at " << this << "\n";
memberFuns["S"] = std::bind(&human::S,this,_1);
memberFuns["I"] = std::bind(&human::I,this,_1);
memberFuns["R"] = std::bind(&human::R,this,_1);
rng.seed(std::random_device()());
};
~human(){
std::cout << "human: " << id << " state: " << state << " being killed at " << this << "\n";
};
void oneStep(){
/* sample a state */
std::uniform_int_distribution<int> rint(0,2);
int sample = rint(rng);
std::cout << "sample : " << sample << "\n";
if(sample==0){state = "S";}
if(sample==1){state = "I";}
if(sample==2){state = "R";}
/* dispatch via function pointers */
memberFuns.at(state)(sample);
};
private:
int id;
std::string state;
std::map<std::string,std::function<void(int)> > memberFuns;
std::mt19937_64 rng;
void S(int num){
std::cout << "human: " << id << " state: " << state << " calling S!\n";
};
void I(int num){
std::cout << "human: " << id << " state: " << state << " calling I!\n";
};
void R(int num){
std::cout << "human: " << id << " state: " << state << " calling R!\n";
};
};
#endif /* human_hpp */
/* main */
#include "human.hpp"
int main(){
std::cout << "staring tests ... \n";
human* person = new human("S",1);
for(size_t i=0; i<10; i++){
person->oneStep();
}
delete person;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment