2010-05-03 130 views
0

我的任務是在C++中創建僞數據庫。有3個表格,商店名稱(char *),年齡(int)和性別(bool)。寫一個程序,允許:
- 新數據添加到表
- 顯示所有記錄
- 排序表與標準:
- 名增加/減少
- 年齡的增加/減少
- 性別C++中簡單的'數據庫'

使用功能模板是必須的。數組的大小也必須是可變的,具體取決於記錄的數量。

我有一些代碼,但仍然存在問題。 以下是我的: 函數tabSize()用於返回數組的大小。但目前它返回指針大小我猜:

#include <iostream> 
using namespace std; 

template<typename TYPE> int tabSize(TYPE *T) 
{ 
    int size = 0; 
    size = sizeof(T)/sizeof(T[0]); 
    return size; 
} 

如何使它返回數組的大小,而不是它的指針?

接下來最重要的是:add()添加新元素。首先我得到數組的大小(但是因此它返回指針的值,而不是現在沒有用的大小:/)。然後我認爲我必須檢查數據類型是否是char。或者我錯了?

// add(newElement, table) 
template<typename TYPE> TYPE add(TYPE L, TYPE *T) 
{ 
    int s = tabSize(T); 
//here check if TYPE = char. If yes, get the length of the new name 
     int len = 0; 
     while (L[len] != '\0') { 
      len++; 
     } 
//current length of table 
    int tabLen = 0; 
    while (T[tabLen] != '\0') { 
     tabLen++; 
    }  
//if TYPE is char 
//if current length of table + length of new element exceeds table size create new table  
    if(len + tabLen > s) 
    { 
     int newLen = len + tabLen; 
     TYPE newTab = new [newLen]; 
     for(int j=0; j < newLen; j++){ 
      if(j == tabLen -1){ 
       for(int k = 0; k < len; k++){ 
        newTab[k] = 
       } 
      } 
      else { 
       newTab[j] = T[j]; 
      } 
     } 
    } 
//else check if tabLen + 1 is greater than s. If yes enlarge table by 1.    
} 

我是否認爲這裏正確?

末功能顯示()是正確的我猜:

template<typename TYPE> TYPE show(TYPE *L) 
{ 
    int len = 0; 
    while (L[len] == '\0') { 
     len++; 
    } 

    for(int i=0; i<len; i++) 
    { 
     cout << L[i] << endl; 
    }  
} 

和問題排序()如下:我何能影響如果排序減少或增加?我在這裏使用冒泡排序。

template<typename TYPE> TYPE sort(TYPE *L, int sort) 
{ 
    int s = tabSize(L);    

    int len = 0; 
    while (L[len] == '\0') { 
     len++; 
    } 
//add control increasing/decreasing sort 
    int i,j; 
    for(i=0;i<len;i++) 
    { 
     for(j=0;j<i;j++) 
     { 
      if(L[i]>L[j]) 
      { 
       int temp=L[i]; 
       L[i]=L[j]; 
       L[j]=temp; 
      } 
     } 
    } 
} 

及主要功能來運行它:

int main() 
{ 
    int sort=0; 
    //0 increasing, 1 decreasing 
    char * name[100]; 
    int age[10]; 
    bool sex[10]; 

    char c[] = "Tom"; 
    name[0] = "John"; 
    name[1] = "Mike"; 

    cout << add(c, name) << endl; 

    system("pause"); 
    return 0; 
} 

回答

0

除非你有某種終止符陣的,有沒有簡單的方法來得到一個數組的大小由T指向。

您將不得不在T指向的數組中循環並計算元素,直到找到終止符。 (大腸桿菌'\0'char *

2

在你的設計中,你必須有一個變量來維護數組的大小。該值將隨着項目添加或刪除而調整。 C++語言沒有用於獲取數組變量大小的功能。

此外,更喜歡使用std::string而不是char *。如果您的教師說要使用char *,則將其作爲參數提供給您的函數,但在函數和類中轉換爲std::string。這會讓你的生活變得更輕鬆。

請勿實施您自己的排序算法。傾向於使用std::sort和不同的比較函數。算法已經過測試,可以節省您的時間和精力。

執行Visitor設計模式。這將允許您以不同的方式訪問表,而無需在表類中編寫新的方法。例如,使用Visitor基類,您可以派生類來讀取文件,寫入文件和顯示內容而不更改表類。

最後,請勿使用system("pause"),這可能不便攜。相反,更喜歡cin.ignore可以在std::istream::ignore找到。

+1

我不會建議在內部存儲'std :: string',除非你先問你的導師(或TA),否則如果賦值說要使用'char *'。在任何現實世界的場景中,你都會想要使用'std :: string',分配的一部分可能是學習手動內存管理,如果他們讀取你的代碼並找到'std :: string',你可能會失去信用。 – 2010-05-03 20:50:18