今天按书上写Josephus的一个解法的程序,但是碰到了无法读取内存的问题
这个是主函数
#include"jose.h"
#include<iostream>
using namespace std;
int main(){
Jose jose;
jose.Initial();
jose.GetWinner();
}
这个是ring.cpp,问题就是在这里,pCurrent和pivot显示无法读取内存
#include"ring.h"
#include<iostream>
#include<iomanip>
using namespace std;
Ring::Ring(int n, int beg){
pBegin = new Boy[n];
pCurrent = pBegin;
for(int i=1; i<=n; i++){
pBegin[i-1].next = pBegin+i%n;
pBegin[i-1].code=i;
PutBoy();
pCurrent = pCurrent->next;
}
pCurrent = &pBegin[n + beg - 2];
}
void Ring::Count(int m)
{
for(int i=1; i<=m; i++)
{
pivot = pCurrent;
pCurrent = pCurrent->next;
}
}
void Ring::PutBoy(bool f) const{
static int numInLine;
if(f){
numInLine = 0;
return ;
}
if(numInLine++%10==0)
cout<<endl;
cout<<setw(4)<<pCurrent->code;
}
void Ring::ClearBoy(){
pivot->next=pCurrent->next;
}
Ring::~Ring(){
delete[] pBegin;
}
void Ring::Display() {
for (Boy* pBegin = pCurrent; (pCurrent = pCurrent->next) != pBegin;)
PutBoy(0);
PutBoy(1);
}
这个是ring.h
#ifndef RING
#define RING
struct Boy{
int code;
Boy* next;
};
class Ring{
public:
Ring(int n, int beg);
void Count(int m);
void PutBoy(bool f=0)const;
void ClearBoy();
void Display();
~Ring();
private:
Boy* pBegin;
Boy* pivot ;
Boy* pCurrent;
};
#endif
下面是另外两个文件
这个是jose.cpp
#include"ring.h"
#include"jose.h"
#include<iostream>
#include<cstdlib>
using namespace std;
//---------------------
void Jose::Initial(){
int num,begin,m;
cout<<"please input the number of boys," \
"begin position,interval per count :\n";
cin>>num>>begin>>m;
if(num<2){
cerr<<"bad number of boys\n";
exit(1);
}
if(begin<0){
cerr<<"bad begin position.\n";
exit(1);
}
if(m<1||m>num){
cerr<<"bad interval number.\n";
exit(1);
}
numOfBoys=num;
beginPos=begin;
interval=m;
}//--------------------
void Jose::GetWinner(){
Ring x(numOfBoys,beginPos);
for(int i=1; i<numOfBoys; i++){
x.Count(interval);
x.PutBoy(0);
x.ClearBoy();
}
x.Count(1);
cout<<"\nthe winner is ";
x.PutBoy(0);
cout<<"\n";
}//--------------------
这个是jose.h
#ifndef JOSE
#define JOSE
class Jose{
public:
Jose(int boys=10, int begin=1, int m=3){
numOfBoys=boys;
beginPos=begin;
interval=m;
}
void Initial();
void GetWinner();
private:
int numOfBoys;
int beginPos;
int interval;
};//-------------------
#endif