-1
這是一個在課堂上給出的任務,我對C++還是比較新的。我們被告知我們必須使用動態數組來創建河內塔計劃。主要開始是這樣的:使用動態陣列的河內塔:如何將新環添加到掛鉤並將掛環移動到掛鉤?
int main()
{
int ring_count, start_peg, end_peg, choice;
bool stay_in_loop = true;
cout << "Enter the number of rings on the first peg:\n" << endl;
cin >> ring_count;
Towers pegs(ring_count);
cout << "The initialized pegs and rings:\n" << pegs << endl;
/* infinite loop for user to enter options to perform
* to solve the tower of hanoi till user asks for exit */
while (stay_in_loop)
{
cout << "Enter 1 to move a ring." << endl;
cout << "Enter 2 to exit the program.\n" << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the ring on which the top ring is to be moved from." << endl;
cin >> start_peg;
cout << "Enter the peg to which the ring needs to moved to." << endl;
cin >> end_peg;
//....etc.
然後有兩個標頭和相應的.cpp文件。一套用於掛釘,一套用於掛環。下面是類的在掛頭體:
public:
/* constructor inits the Peg
* with n rings. The diameter peg's
* rings are from one inch(on top) to
* nth inch(on the bottom). */
Peg(size_t n);
/* returns the number of rings on the peg. */
size_t many_rings()const;
/* returns the value of the diameter of the top most ring. */
size_t top_diameter()const;
/* adds a new ring to the peg. */
void add_ring_to_top(const value_type ring_diameter);
/* remove the topmost ring of the peg */
void remove_top_ring();
/* overload output operator to print the peg object
* along with its rings in a understable format. */
friend ostream& operator << (ostream& os, const Peg& p);
protected:
/* use appropriate data structure for the pegs */
value_type top_most;
size_type ringUsed;
size_type ringCapacity;
int *arr = new int[ringCapacity];
bool legal; // for telling move_ring function if the move is legal
在環頭有一個函數:int move_ring(int start_peg, int end_peg);
我的問題是這樣的:我如何使用這個代碼是給我們創建add_ring_to_top
和move_ring
函數的主體,而不具有不同的陣列,ringUsed
用於每個掛鉤。我已經研究了很長一段時間,我不需要整個解決方案,但有些方向將不勝感激。如果我應該使用這些typedef
,請幫助我瞭解這些特定程序如何使用這些程序,但我沒有經驗。
爲什麼你不應該爲每個peg有不同的數組和'ringUsed'? – molbdnilo
我不知道,我只是認爲應該這樣做,因爲我給出的所有起始代碼都只有一個。 – Rhuen