2010-05-03 128 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