#include <functional>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <memory>

using namespace std;

auto foo(int bar)
{
    const char t = 'A' + bar;
    return [=](int b)->char {
        const char res = t + b;
        return res;     
    };
}
auto counter(int initial)
{
    shared_ptr<int> pct(new int{ initial });
    unordered_map<string, function<int()> > functions;
    functions["reset"] = [=]()->int {
        *pct = initial;
        return *pct;
    };
    functions["next"] = [=]()->int {
        return (*pct)++;
    };
    return functions;
}

int main(int argc, char * argv[])
{
    const int tests = 8;
    //产生8个闭包
    vector<function<char(int)> > vec_closures;
    for (int i = 0; i < tests; ++i)
        vec_closures.push_back(foo(i));
    //多线程集中调用
#pragma omp parallel for
    for (int i = 0; i < tests; ++i)
    {
        const char res = vec_closures[i](i + 1);
        cout <<  res;
    }
    cout << endl;
    //单线程集中调用
    for (int i = 0; i < tests; ++i)
    {
        const char res = vec_closures[i](i + 1);
        cout << res;
    }
    cout << endl;
    
    auto counter_a = counter(10);
    auto counter_b = counter(100);
    cout << counter_a["next"]()<<endl;
    cout << counter_a["next"]() << endl;
    cout << counter_b["next"]() << endl;
    cout << counter_b["next"]() << endl;
    counter_a["reset"]();
    cout << counter_a["next"]() << endl;
    cout << counter_b["next"]() << endl;
    return 0;
}
