我的任务是在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