Templates and small error
Mar 14, 2011 at 5:13pm UTC
I have this code where I add 5 numbers to an array.
I have a problem with removing.
I'm supposed to remove the first value in the array, but it's not doing that. Also, I have to add a char variable to the array as well, that threw me off since I don't know how to make that work and it's giving definition errors. I have to use templates too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
#include <iostream>
using namespace std;
template <class T>
class list
{
private :
#define MAXSIZE 50
T ar[MAXSIZE];
int number;
public :
list();
bool isFull();
bool isEmpty();
void add(T x);
void display();
T remove();
};
template <class T>
list<T>::list()
{
number = 0;
}
template <class T>
bool list<T>::isEmpty()
{
return (number == 0);
}
template <class T>
bool list<T>::isFull()
{
return (number == MAXSIZE);
}
template <class T>
void list<T>::add(T x)
{
ar[number] = x;
number++;
}
template <class T>
T list<T>::remove()
{
number--;
return ar[number];
}
template <class T>
void list<T>::display()
{
for (int i = 0; i < MAXSIZE; i++)
{
cout << ar[i] << endl;
}
}
int main()
{
list <int > numList;
numList.add(100);
numList.add(90);
numList.add(80);
numList.add(70);
numList.add(60);
numList.add("k" );
numList.remove();
numList.display();
system("pause" );
return 0;
}
Can anyone help me here? :O
Thanks!
Mar 14, 2011 at 5:50pm UTC
1) Your remove function as it stands removes the last element of the array. To remove the first you would have to shift everything over.
2) You aren't adding a char variable there, you are adding a string literal. Characters use single quotes: ' ' and string literals use " ".
Mar 14, 2011 at 10:26pm UTC
Do you know how I can shift everything over?
Mar 14, 2011 at 10:29pm UTC
Also, I still don't get k showing up.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
list <int > numList;
list <char > charList;
numList.add(100);
numList.add(90);
numList.add(80);
numList.add(70);
numList.add(60);
charList.add('k' );
numList.remove();
numList.display();
system("pause" );
return 0;
}
Mar 14, 2011 at 11:37pm UTC
Erm, that's because you add it to charList, which you never print out, I think.
Mar 15, 2011 at 12:00am UTC
Okay, I see that now.
Does anyone know how to delete the first value in an array and shift everything over?
Topic archived. No new replies allowed.