Hi all! I'm working on writing a Display() function for a templates class program. The Display() function is a templated client function, not a part of the class, and is supposed to take in an argument called a_set and display the contents of the set. However, I am having trouble doing this. I've tried writing the function a few ways, but I would always get the wrong output. Down below I will provide you with the Display function I have written inside the Set.cpp file (not the main.cpp), and after the class implementation.
1 2 3 4 5 6 7 8 9 10
template <class ItemType> // this function displays the set
void DisplaySet(const Set<ItemType> &a_set) {
int size = a_set.GetCurrentSize(); //gets size of the set
cout << size << endl; //just to check
int array[size]; //not sure if this is what I'm supposed to do
for (int i = 0; i < size; i++) {
cout << array[i] << endl; //I'm assuming I would need a for loop
} //because I am working with array based implementations
}
This is what I would have in my set (in the main.cpp file)
So the DisplaySet() function should display 1, 10, 3, 5. (My Add() function gets rid of duplicate numbers). However, I tend to get output along the lines of hexadecimal numbers or
1606415488
32767
7880
.
If any of you need to look at any of my implementation files for further reference, let me know. Many thanks!
int array[size]; //not sure if this is what I'm supposed to do
for (int i = 0; i < size; i++) {
cout << array[i] << endl; //I'm assuming I would need a for loop
}
The output here is undefined. You create an array witch by default is filled with garbage values. Then you output those values.
Thank you for your reply, Yanson. So basically what I am doing now is just outputting the garbage values from the array in the function rather than from the array in the actual set? How then would I go about outputting the values I actually want to output? Would I have to include an int array as one of the parameters for the DisplaySet() function? Or is there a way I can display the contents of a_set (referring to the function parameter in DisplaySet()) without using an array? So something like:
1 2 3 4 5
template <class ItemType> // this function displays the set
void DisplaySet(const Set<ItemType> &a_set) {
cout << a_set << endl; //something along the lines of this? Without arrays
}