貓吃老鼠的STL實(shí)現(xiàn)方法

字號(hào):

一、看到貓吃老鼠問(wèn)題,感覺(jué)如果用STL將更加簡(jiǎn)單。在實(shí)現(xiàn)時(shí)將問(wèn)題稍作修改,變成總共n個(gè)老鼠,每隔m個(gè)吃一個(gè),求最后剩下哪一個(gè),并用STL實(shí)現(xiàn)。
    二、代碼
    #include < vector >
    #include < iostream >
    using namespace std;
    int eat(const int total, const int space)
    {
    if (total <= 0 || space <= 0)
    {
    return -1;
    }
    vector v;
    vector::iterator it;
    // 初使化向量
    for (int i = 1; i <= total; ++i)
    {
    v.push_back(i);
    }
    int j = 1;
    it = v.begin();
    while (v.size() > 1)
    {
    // 如果數(shù)到第m個(gè),則刪除它,并且從頭開(kāi)始數(shù)
    // 迭代器不需要后移,因?yàn)閯h除之后自動(dòng)就指向下一個(gè)元素
    if (space == j)
    {
    v.erase(it);
    j = 1;
    }
    else
    {
    ++it;
    ++j;
    }
    // 如果到最后了,讓迭代器指向第一個(gè)元素
    if (it >= v.end())
    {
    it = v.begin();
    }
    }
    // 現(xiàn)在只有一個(gè)元素了,那么第一個(gè)元素就是我們需要的
    return (*v.begin());
    }
    void main( void )
    {
    int total;
    int space;
    total = 5;
    space = 1;
    cout << \"總共: \" << total << \" \"
    << \"間隔: \" << space << \" \"
    << \"最后: \" << eat(total, space) << endl;
    total = 5;
    space = 2;
    cout << \"總共: \" << total << \" \"
    << \"間隔: \" << space << \" \"
    << \"最后: \" << eat(total, space) << endl;
    total = 5;
    space = 3;
    cout << \"總共: \" << total << \" \"
    << \"間隔: \" << space << \" \"
    << \"最后: \" << eat(total, space) << endl;
    }