2014-12-12 2 views
-2

저는 함수 배열을 만드는 방법을 찾기 위해 잠시 노력해 왔습니다. 나는 엑스 코드를 사용하고, 내가하려고 할 때마다, 그것은 경고 나 메시지를 표시함수 배열을 추가하고 임의로 하나를 선택하십시오.

예상 "("함수 스타일 캐스트 또는 유형 건축.

을 위해 나는 무엇을 정확하게 너무 확실하지 않다 그것에 대해 할. 여기에 코드의 샘플입니다.

//possibleResponses 

int Responses[]{ //this is where the error is. 

int possibleResponse1; 
{ 
    cout << "Continue...\n"; 
    getline (cin, inputc); 
} 

int possibleResponse2 (0); 
{ 
    cout << "Text" << inputb << ".\n"; 
    getline (cin, inputd); 
} 

가 명확히하기 위해, 나는 내 프로그램. 내가 배열이 위치하게 한 후, 출력을 무작위 싶습니다 줄 수있는 20여 가능한 반응을 가지고있다. 그것은 것 누군가가 나를 도울 수 있다면 훌륭 할 것입니다 (가능한 경우, 샘플 대구를 첨가하십시오 e, 나는 그 방법을 더 잘 배운다), 미리 감사드립니다!

답변

0

내가 게시 한 코드로 무엇을했는지 확신 할 수 없지만 컴파일되지 않을 것이라고 확신합니다. 나는 "함수들의 배열을 추가하고 무작위로 하나를 선택하는"방법을 보여 주려고 노력할 것이다.

int function1() { ... } // implementation is irrelevant 
int function2(int x) { ... } 
int function3(char x) { ... } 

클라이언트 코드 :

#include <functional> 
#include <vector> 

std::vector<std::function<int(void)>> functions; // all functions placed 
               // in here take no parameters 

functions.push_back(function1); 
functions.push_back([]() { return function2(190); }); // adaptor functor, calling 
                 // function2 with parameters 
                 // the adaptor matches the 
                 // signature of 
                 // functions::value_type 
functions.push_back([]() { return function3('s'); }); // same as above 

순서에서 임의의 함수를 호출 :

#include <random> 

std::random_device rd; 
static std::mt19937 gen(rd()); // mersene twister 
std::uniform_int_distribution<> d(0, functions.size()); 
auto itr = std::begin(functions); 
std::advance(itr, dis(gen)); // advance iterator by random number of positions 

(*itr)(); // call the functor 

또는 :

#include <random> 

std::random_device rd; 
static std::mt19937 gen(rd()); // mersene twister 
std::uniform_int_distribution<> d(0, functions.size()); 
auto index = dis(gen)); // get index in range [0, functions.size()) 

functions[index](); 

깨끗한 코드를 유지하려면, 배치하는 것이 좋습니다 당신의 네임 스페이스의 응답 함수 (leas t) :

namespace responses { 
    int function1() { ... } // implementation is irrelevant 
    int function2(int x) { ... } 
    int function3(char x) { ... } 
} 
관련 문제