Hello. My task was to create pseudodatabase in c++. There are 3 tables given, that store name(char*), age(int), and sex (bool). Write a program allowing to :
- add new data to the tables
- show all records
- sort tables with criteria :
- name increasing/decreasing
- age increasing/decreasing
- sex
Using function templates is a must. Also size of arrays must be variable, depending on the amount of records.
I have some code but there are still problems there. Here's what I have: Function tabSize() for returning size of array. But currently it returns size of pointer I guess :
#include <iostream>
using namespace std;
template<typename TYPE> int tabSize(TYPE *T)
{
int size = 0;
size = sizeof(T) / sizeof(T[0]);
return size;
}
How to make it return size of array, not its pointer ?
Next the most important : add() for adding new elements. Inside first I get the size of array (but hence it returns value of pointer, and not size it's of no use now :/). Then I think I must check if TYPE of data is char. Or am I wrong ?
// 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.
}
Am I thinking correct here ?
Last functions show() is correct I guess :
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;
}
}
and problem with sort() is as follows : Ho can I influence if sorting is decreasing or increasing ? I'm using bubble sort here.
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;
}
}
}
}
And main function to run it :
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;
}