一、看到貓吃老鼠問題,感覺如果用STL將更加簡單。在實(shí)現(xiàn)時將問題稍作修改,變成總共n個老鼠,每隔m個吃一個,求最后剩下哪一個,并用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個,則刪除它,并且從頭開始數(shù)
// 迭代器不需要后移,因?yàn)閯h除之后自動就指向下一個元素
if (space == j)
{
v.erase(it);
j = 1;
}
else
{
++it;
++j;
}
// 如果到最后了,讓迭代器指向第一個元素
if (it >= v.end())
{
it = v.begin();
}
}
// 現(xiàn)在只有一個元素了,那么第一個元素就是我們需要的
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;
}
二、代碼
#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個,則刪除它,并且從頭開始數(shù)
// 迭代器不需要后移,因?yàn)閯h除之后自動就指向下一個元素
if (space == j)
{
v.erase(it);
j = 1;
}
else
{
++it;
++j;
}
// 如果到最后了,讓迭代器指向第一個元素
if (it >= v.end())
{
it = v.begin();
}
}
// 現(xiàn)在只有一個元素了,那么第一個元素就是我們需要的
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;
}