zoukankan      html  css  js  c++  java
  • C++ 模板实现约瑟夫环

    使用了模板:vector、list、deque进行比较

    #include <iostream>
    #include <vector>
    #include <list>
    #include <deque>
    #include <typeinfo>
    #include <ctime>
    using namespace std;
    
    template<class T>
    void Joseph(T collection,int n,int m)
    {
        if(n < 1 || m < 1)
        {
            cout << "Error input number!" << endl;
            return;
        }
        for(int i = 1;i <= n;i++)
            collection.push_back(i);
        class T::iterator iter = collection.begin(),del;
        int counter = 1;
        clock_t start = clock(),finish;
        while(collection.size() > 1)
        {
            while (counter % m == 0 && collection.size() > 1)
            {
                counter = 1;
                if (typeid(collection)!=typeid(list<int>))
                    iter = collection.erase(iter);
                else
                {
                    del = iter;
                    iter++;
                    collection.erase(del);
                }
                if(iter == collection.end())
                    iter = collection.begin();
            }
            counter++;
            iter++;
            if(iter == collection.end())
                iter = collection.begin();
        }
        finish = clock();
        cout << "最后剩余的人的编号是:"  << *iter <<endl;
        //CLOCKS_PER_SEC是标准c的time.h头函数中宏定义的一个常数,表示一秒钟内CPU运行的时钟周期数,
        //用于将clock()函数的结果转化为以秒为单位的量,但是这个量的具体值是与操作系统相关的。
        cout << "使用容器 " << typeid(collection).name() << " 的运算时间为;" << 1.0*(finish-start)/CLOCKS_PER_SEC << "秒" <<endl;
    }
    int main()
    {
        list <int>l;
        vector <int > v;
        deque <int> d;
        Joseph(l,100000,5);
        Joseph(d,100000,5);
        Joseph(v,100000,5);
        return 0;
    }
    
    
  • 相关阅读:
    Silverlight开发“慢”游美丽的分形世界(画分形2)
    c#进阶methods中3explicit和implicit
    C#进阶可选参数和命名参数
    Silverlight杂记自定义loading
    c#进阶params可变个数的参数
    Abundant Resources
    欧拉函数
    容斥原理 讲解
    sdut 2497 A simple problem (并查集 or dfs)
    hdu 4366 Card Collector (容斥原理)
  • 原文地址:https://www.cnblogs.com/Jesse-Cavendish/p/14528742.html
Copyright © 2011-2022 走看看