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