I am attempting to write a template/class that has a few functions, but I’m running into what seems like a rather newbie problem. I have a simple insert function and a display values function, however whenever I attempt to display the value, I always receive what looks like a memory address(but I have no idea), but I would like to receive the value stored (in this particular example, the int 2). I’m not sure how to dereference that to a value, or if I’m just completely messing up. I know that vectors are a better alternative, however I need to use an array in this implementation – and honestly I would like to gain a more thorough understanding of the code and what’s going on. Any help as to how to accomplish this task would be greatly appreciated.
Example Output (running the program in the same way every time):
003358C0
001A58C0
007158C0
Code:
#include <iostream>
using namespace std;
template <typename Comparable>
class Collection
{
public: Collection() {
currentSize = 0;
count = 0;
}
Comparable * values;
int currentSize; // internal counter for the number of elements stored
void insert(Comparable value) {
currentSize++;
// temparray below is used as a way to increase the size of the
// values array each time the insert function is called
Comparable * temparray = new Comparable[currentSize];
memcpy(temparray,values,sizeof values);
// Not sure if the commented section below is necessary,
// but either way it doesn't run the way I intended
temparray[currentSize/* * (sizeof Comparable) */] = value;
values = temparray;
}
void displayValues() {
for (int i = 0; i < currentSize; i++) {
cout << values[i] << endl;
}
}
};
int main()
{
Collection<int> test;
int inserter = 2;
test.insert(inserter);
test.displayValues();
cin.get();
return 0;
}
Well, if you insist, you can write and debug your own limited version of
std::vector.First, don’t
memcpyfrom an uninitialized pointer. Setvaluestonew Comparable[0]in the constructor.Second,
memcpythe right number of bytes:(currentSize-1)*sizeof(Comparable).Third, don’t
memcpyat all. That assumes thatComparabletypes can all be copied byte-by-byte, which is a severe limitation in C++. Instead:EDIT: changed
uninitialized_copytocopy:Fourth, delete the old array when it’s no longer in use:
Fifth, unless the code is going to make very few insertions, expand the array by more than one.
std::vectortypically increases its size by a factor of 1.5.Sixth, don’t increment
currentSizeuntil the size changes. That will change all thosecurrentSize-1s intocurrentSize, which is much less annoying.<g>Seventh, an array of size
Nhas indices from0toN-1, so the top element of the new array is atcurrentSize - 1, notcurrentSize.Eighth, did I mention, you really should use
std::vector.