Placing the contents of a linked list in an array reference - c++

My instructions are...
// Description: Places the payload contents of the list in the
// array referenced by 'populateMeWithElements'.
// Returns the number of elements that were placed
// in the provided memory location.
// Precondition: Enough memory has been allocated to the provided
// memory location to hold the full contents
// of the list.
// Postcondition: The memory allocated for 'populateMeWithElements'
// has been deallocated after the completion of
// this method call.
int getListElements(int* populateMeWithElements);
I have this written...
int OOLList::getListElements(int* populateMeWithElements) {
int count = 0;
OOLNode* iterator = this->start;
int* populateMeWithElements = new int[getListSize()];
for (int i = 0; iterator->next != NULL; i++) {
populateMeWithElements[i] = iterator->payload;
iterator = iterator->next;
count++;
}
return count;
}
but I am not sure if it is correct and if it is...
How do I display the contents in my driver
Where I deallocate the memory (do I do this in the driver or in the function that I wrote?)
Thanks in advance for any suggestions or help.

Your function is declaring a local populateMeWithElements variable that shadows the input populateMeWithElements parameter. You are filling the array that you allocate locally, you are not populating the caller's array at all.
For that matter, your function should not be using new[] at all, since the instructions clearly state that the precondition of the function is that the caller has already allocated an array of sufficient size beforehand, and will deallocate that array after the function exits. So, your function's job is merely to fill the caller's array, nothing more.
And on that task, your loop is wrong. iterator->next != NULL needs to be iterator != NULL, otherwise if the list is empty then the 1st access of iterator->next will fail, and if the list is not empty then the payload of the tail node will be skipped.
Try this instead:
int OOLList::getListElements(int* populateMeWithElements) {
int count = 0;
OOLNode* iterator = this->start;
for (int i = 0; iterator != NULL; i++) {
populateMeWithElements[i] = iterator->payload;
iterator = iterator->next;
++count;
}
return count;
}
OOLList list;
// populate list as needed...
int* elements = new int[list.getListSize()];
int count = list.getListElements(elements);
for(int i = 0; i < count; ++i) {
// use elements[i] as needed...
}
delete[] elements;
The function can be simplified a bit further:
int OOLList::getListElements(int* populateMeWithElements) {
int count = 0;
for (OOLNode* iterator = this->start; iterator != NULL; iterator = iterator->next) {
populateMeWithElements[count++] = iterator->payload;
}
return count;
}
Or even:
int OOLList::getListElements(int* populateMeWithElements) {
int* ptr = populateMeWithElements;
for (OOLNode* iterator = this->start; iterator != NULL; iterator = iterator->next) {
*ptr++ = iterator->payload;
}
return ptr - populateMeWithElements;
}

Related

Delete Zero in ArrayList in C++

Inside the ArrayList I'm trying to delete all possible 0's that are appended as input, but for now it only deletes just one 0, no matter where it is located. But seems like I can't delete more than one zero at the time. How can I fix this?
void AList::elimZeros(){
int i;
int curr = 0;
for(i=0; i < listSize; i++) {
if ( (listArray[i] != 0 ) && (curr<listSize) ){
listArray[curr] = listArray[i];
curr++;
}
else if (listArray[i] == 0 )
{
listArray[curr] = listArray[i+1];
listSize--;
curr++;
}
}
}
This is the class for the ADT
class AList : public List {
private:
ListItemType* listArray; // Array holding list elements
static const int DEFAULT_SIZE = 10; // Default size
int maxSize; // Maximum size of list
int listSize; // Current # of list items
int curr; // Position of current element
// Duplicates the size of the array pointed to by listArray
// and update the value of maxSize.
void resize();
public:
// Constructors
// Create a new list object with maximum size "size"
AList(int size = DEFAULT_SIZE) : listSize(0), curr(0) {
maxSize = size;
listArray = new ListItemType[size]; // Create listArray
}
~AList(); // destructor to remove array
This is the input I'm testing with:
int main() {
AList L(10);
AList L2(20);
L.append(10);
expect(L.to_string()=="<|10>");
L.append(20);
expect(L.to_string()=="<|10,20>");
L.append(30);
L.append(0);
L.append(40);
L.append(0);
L.append(0);
expect(L.to_string()=="<|10,20,30,0,40>");
L.elimZeros();
expect(L.to_string()=="<|10,20,30,40>");
assertionReport();
}
It'd be helpful if you posted the class code for AList. Think you confused Java's ArrayList type, but assuming you're using vectors you can always just do:
for (int i = 0; i < listSize; i++) {
if(listArray[i] == 0) listArray.erase(i);
}
EDIT: Assuming this is the template of for the AList class, then there is simply a remove() function. In terms of your code, there are two issues.
You reference listSize in the for loop, then decrement it inside of the loop. Each iteration evaluates the value separately so you're reducing the number of total loop iterations and stopping early.
The other thing is if the entry is zero you shouldn't increment curr and set listArray[curr] = listArray[i+1]. This is basically assuming the next entry will not be a zero. So if it is, then you're copying the element and moving to the next. Your if statement can be cleaned up with:
if (listArray[i] == 0) {
listSize--;
} else {
listArray[curr] = listArray[i];
curr++;
}

Array of Linked Lists C++

So I thought I understood how to implement an array of pointers but my compiler says otherwise =(. Any help would be appreciated, I feel like I'm close but am missing something crucial.
1.) I have a struct called node declared:.
struct node {
int num;
node *next;
}
2.) I've declared a pointer to an array of pointers like so:
node **arrayOfPointers;
3.) I've then dynamically created the array of pointers by doing this:
arrayOfPointers = new node*[arraySize];
My understanding is at this point, arrayOfPointers is now pointing to an array of x node type, with x being = to arraySize.
4.) But when I want to access the fifth element in arrayOfPointers to check if its next pointer is null, I'm getting a segmentation fault error. Using this:
if (arrayOfPointers[5]->next == NULL)
{
cout << "I'm null" << endl;
}
Does anyone know why this is happening? I was able to assign a value to num by doing: arrayOfPointers[5]->num = 77;
But I'm confused as to why checking the pointer in the struct is causing an error. Also, while we're at it, what would be the proper protoype for passing in arrayOfPointers into a function? Is it still (node **arrayOfPointers) or is it some other thing like (node * &arrayOfPointers)?
Thanks in advance for any tips or pointers (haha) you may have!
Full code (Updated):
/*
* Functions related to separate chain hashing
*/
struct chainNode
{
int value;
chainNode *next;
};
chainNode* CreateNewChainNode (int keyValue)
{
chainNode *newNode;
newNode = new (nothrow) chainNode;
newNode->value = keyValue;
newNode->next = NULL;
return newNode;
}
void InitDynamicArrayList (int tableSize, chainNode **chainListArray)
{
// create dynamic array of pointers
chainListArray = new (nothrow) chainNode*[tableSize];
// allocate each pointer in array
for (int i=0; i < tableSize; i++)
{
chainListArray[i]= CreateNewChainNode(0);
}
return;
}
bool SeparateChainInsert (int keyValue, int hashAddress, chainNode **chainListArray)
{
bool isInserted = false;
chainNode *newNode;
newNode = CreateNewChainNode(keyValue); // create new node
// if memory allocation did not fail, insert new node into hash table
if (newNode != NULL)
{
//if array cell at hash address is empty
if (chainListArray[hashAddress]->next == NULL)
{
// insert new node to front of list, keeping next pointer still set to NULL
chainListArray[hashAddress]->next = newNode;
}
else //else cell is pointing to a list of nodes already
{
// new node's next pointer will point to former front of linked list
newNode->next = chainListArray[hashAddress]->next;
// insert new node to front of list
chainListArray[hashAddress]->next = newNode;
}
isInserted = true;
cout << keyValue << " inserted into chainListArray at index " << hashAddress << endl;
}
return isInserted;
}
/*
* Functions to fill array with random numbers for hashing
*/
void FillNumArray (int randomArray[])
{
int i = 0; // counter for for loop
int randomNum = 0; // randomly generated number
for (i = 0; i < ARRAY_SIZE; i++) // do this for entire array
{
randomNum = GenerateRandomNum(); // get a random number
while(!IsUniqueNum(randomNum, randomArray)) // loops until random number is unique
{
randomNum = GenerateRandomNum();
}
randomArray[i] = randomNum; // insert random number into array
}
return;
}
int GenerateRandomNum ()
{
int num = 0; // randomly generated number
// generate random number between start and end ranges
num = (rand() % END_RANGE) + START_RANGE;
return num;
}
bool IsUniqueNum (int num, int randomArray[])
{
bool isUnique = true; // indicates if number is unique and NOT in array
int index = 0; // array index
//loop until end of array or a zero is found
//(since array elements were initialized to zero)
while ((index < ARRAY_SIZE) && (!randomArray[index] == 0))
{
// if a value in the array matches the num passed in, num is not unique
if (randomArray[index] == num)
{
isUnique = false;
}
index++; // increment index counter
} // end while
return isUnique;
}
/*
*main
*/
int main (int argc, char* argv[])
{
int randomNums[ARRAY_SIZE] = {0}; // initialize array elements to 0
int hashTableSize = 0; // size of hash table to use
chainNode **chainListArray;
bool chainEntry = true; //testing chain hashing
//initialize random seed
srand((unsigned)time(NULL));
FillNumArray(randomNums); // fill randomNums array with random numbers
//test print array
for(int i = 0; i < ARRAY_SIZE; i++)
{
cout << randomNums[i] << endl;
}
//test chain hashing insert
hashTableSize = 19;
int hashAddress = 0;
InitDynamicArrayList(hashTableSize, chainListArray);
//try to hash into hash table
for (int i = 0; i < ARRAY_SIZE; i++)
{
hashAddress = randomNums[i] % hashTableSize;
chainEntry = SeparateChainInsert(randomNums[i], hashAddress, chainListArray);
}
system("pause");
return 0;
}
arrayOfPointers = new node*[arraySize];
That returns a bunch of unallocated pointers. Your top level array is fine, but its elements are still uninitialized pointers, so when you do this:
->next
You invoke undefined behavior. You're dereferencing an uninitialized pointer.
You allocated the array properly, now you need to allocate each pointer, i.e.,
for(int i = 0; i < arraySize; ++i) {
arrayOfPointers[i] = new node;
}
As an aside, I realize that you're learning, but you should realize that you're essentially writing C here. In C++ you have a myriad of wonderful data structures that will handle memory allocation (and, more importantly, deallocation) for you.
Your code is good, but it's about how you declared your InitDynamicArrayList. One way is to use ***chainListArray, or the more C++-like syntax to use references like this:
void InitDynamicArrayList (int tableSize, chainNode **&chainListArray)

Trying to push a value using a dynamic array in c++

I'm trying to write a function that pushes an item onto the end of my dynamically allocated array (not allowed to use vectors). Once it goes to the area to double the size of the list if the list was too small to store the next number, it all goes to hell and starts feeding me back random numbers from the computer. Can anyone see why it's not doubling like it's suuposed to?
int *contents_;
int *temp;
int size_ = 0;
int capacity_ = 1;
void pushBack(int item) /**appends the specified value to DynArray; if the contents array is full,
double the size of the contents array and then append the value **/
{
if (size_ == capacity_)
{
capacity_ = (2*capacity_);
temp = new int[capacity_];
for (int i = 0; i < size_; ++i)
{
temp[i] = contents_[i];
}
delete [] contents_;
contents_ = temp;
}
contents_[size_++] = item;
}
EDIT ** I forgot to mention. This is a function out of a class. This is in the header and in main :
main()
{
DynArray myArray;
myArray.pushBack(2);
myArray.pushBack(3);
myArray.printArray();
return 0;
}
If this is your initial setup:
int *contents_; // Junk
int size_ = 0;
int capacity_ = 1;
Then your code is most likely performing a memory access violation upon the first time it does:
if (size_ == capacity_)
{
// Not entering here, contents_ remains junk
}
contents_[size_++] = item;
As barak implied, the contents_ pointer needs to be initialized. If not, c++ will point it to something you probably don't want it to.

vector iterators incompatible Vector Line 251

I am debugging a code dealing with vectors and iterators. I get an assertion error when I am clicking the "New" button on my GUI. The assertion error is that in the title, with the addition of /vector Line 251.
I have traced the problem to a part of the code attempting to remove an element from a vector. I will post the entire function and then the line that bugs:
int VsuCNTreeNodeManager::deleteTreeNode(RWCString & CNNameToDelete, RWTValSlist<VsuDeletedCN> & deletedCNList)
{
RWCString childName, parentName;
VsuCNTreeNode *pNode;
int i;
int size;
if (!nodeList.contains(CNNameToDelete))
return 1; // Means that CNNameToDelete doest not exist.
pNode = ordCNList[nodeList[CNNameToDelete]];
travForName.reset();
travForName.processElement(pNode);
const RWTValSlist<RWCString> & childNameList = travForName.getNameList();
size = childNameList.entries();
// If it is the Top node that is deleted then
// the VsuCNTreeNodeManager's top node pointer is reset.
if ( pNode == pTopCNTreeNode )
{
pTopCNTreeNode = NULL;
}
for ( i = 0; i < size; i++)
{
//******* How would it possible to have a name not contained in the nodeList
//******* since it has been extracted from the nodeList ?????????????
childName = childNameList.at(i);
if (nodeList.contains(childName))
{
//******* Process that get the Parent List of each deleted Tree Node
//******* The following code unref all the Tree Nodes that was referencing any deleted Tree Node
pNode = ordCNList[nodeList[childName]]; // Get the Tree Node to be deleted
// Fill the deletedCNList
deletedCNList.insert( VsuDeletedCN(childName, pNode->getCN()->hasType()) );
VsuDependencyRemoverVisitor visitor( *pNode );
for (unsigned int k = 0; k < pNode->getParentList().entries(); k++)
{
parentName = pNode->getParentList().at(k)->getCN()->getName();
if ( nodeList.contains(parentName) ) // Check if the parent is not deleted
{
//*** Remove the reference of the deleted tree node from that parent
RWBoolean status;
status = ordCNList[nodeList[parentName]]->removeElem(childName); // Removing the reference that pNode(parent) had on key(Child)
}
}
//******* Remove references on this object from observers.
pNode->resetObserverFlags();
pNode->updateAllObservers(&visitor);
//******* Process that delete all the Tree Nodes in the parentList
nodeList.remove(childName);
}
}
//*****************update Lists********************
size = ordCNList.entries();
int index = 0;
RWTValHashDictionary<RWCString, int> tmpNodeList(rwhash);
//nodeList.clear();
RWTPtrOrderedVector<VsuCNTreeNode> nodeToDelete(childNameList.entries());
for(i = 0; i < size; i++)
{
pNode = ordCNList[index];
childName = pNode->getCN()->getName();
if (!childNameList.contains(childName))
{
tmpNodeList.insertKeyAndValue(childName, index);
index++;
}
else
{
ordCNList.remove(pNode);
typeList[pNode->getCN()->hasType()].treeNodeList.remove(pNode);
// Decrement type counter and if it reach 0 then
// the entry is removed.
if( !typeList[pNode->getCN()->hasType()].treeNodeList.entries() )
typeList.remove(pNode->getCN()->hasType());
nodeToDelete.insert(pNode);
}
}
nodeList.clear();
nodeList = tmpNodeList;
ordCNList.resize(index);
if (!index)
pTopCNTreeNode = NULL;
for( unsigned int j=0; j < nodeToDelete.entries(); j++)
{
delete nodeToDelete[j];
}
return 0;
}
Now the line that bugs is:
RWBoolean status;
status = ordCNList[nodeList[parentName]]->removeElem(childName);
The definition of the removeElem function is:
RWBoolean VsuVE_Collection::removeElem(const RWCString & data)
{
VsuVE_Moveable *pMyObj = elementList.at(nameList[data]);
return removeElem1(pMyObj);
}
The definition of removeElem1 is:
RWBoolean VsuVE_Collection::removeElem1(VsuVE_Moveable *elem)
{
if (elementList.remove(elem) == FALSE) // THE ASSERTION ERROR HAPPENS RIGHT HERE
return FALSE;
//**** Reordering the nameList
nameList.clear();
int size = elementList.entries();
for (int i = 0; i < size; i++)
{
nameList.insertKeyAndValue(elementList.at(i)->name, i);
}
return TRUE;
}
My guess is that the removeElem function is attempting to remove a vector element that isn't there or that is out of the index range, but I am unable to figure out where exactly I can fix this. Any help is appreciated.
Thanks in advance
It's not obvious which particular framework you're using here (Rogue Wave?), but I think it may be possible to deduce the problem.
The key to decoding this assertion is understanding what incompatible iterators means. In general it means that you're trying to do an operation on a pair of items that don't refer to the same thing. For instance: (with standard library containers)
std::vector<int> v1, v2;
for (auto it=v1.begin(); it!=v2.end(); it++) { // <=== iterator incompatible
}
std::vector<int>::iterator it1=v1.begin();
v2.erase(v1); // <==== iterator incompatible
If you dig into the definition of the iterator types you have, then you should find that when the iterator is created it stores a reference back to the container it was created from. If you then perform an operation on two iterators (as in the first case above) then it can detect that they refer to different containers and hence aren't compatible. In the second case you have an operation on a container and an iterator, and so again it will assert that the iterator refers to that container.
In your case it appears that you're trying to remove an element from a container. The framework is asserting that the item isn't in the container (and in fact is probably in another). I suspect that you're deleting an item from the wrong container.

No Appropriate Default Constructor Available despite default constructor made?

Trying to make my own Map struct to store my own-created 'Strings,' and after 8 hours or so finally got it down to only a few compiler errors (six of them). I've spent the last hour and forty minutes searching the web for answers, only to find people forgot default constructors, and tried mixing things up in my own program. Since I'm not really sure where the problem is in advance, I apologize for posting all this code...I put what I thought were the most relevant files first; I think only the first 3 are necessary. The error is
"SubdomainPart' : No appropriate default constructor available" for lines 12 and 20 of the Map.h file.
Map.h
// Map.h - Map template class declaration
// Written by -----
#pragma once
template<typename KEY_TYPE, typename VALUE_TYPE>
struct Map
{
public:
// Default / initial constructor hybrid
Map(int initialCapacity = 10)
{
Size = 0;
Capacity = initialCapacity;
Key;
MappedValue;
//Allocate the C-Array elements using HEAP
Data = new VALUE_TYPE[Capacity];
}
struct iterator
{
KEY_TYPE * current;
KEY_TYPE * prev;
KEY_TYPE * next;
iterator operator ++ ()
{
iterator it = this;
iterator itNext = it.next;
it.next = itNext.next; // pushes iterator forward.
it.prev = it.current;
it.current = it.next;
}
iterator operator -- ()
{
iterator it = this;
iterator itPrev = it.prev;
it.prev = itPrev.prev; // pushes iterator backward.
it.next = it.current;
it.current = it.prev;
}
};
Map(const Map& copyFrom)
{
// Necessary to prevent the delete[] Data; statement in the assignment operator from
// freezing because Data has some garbage address in it.
Data = NULL;
*this = copyFrom; //'this' points to the current instance of the object. (in this case, 'Map')
}
// Destructor: MUST HAVE because we allocate memory
~Map()
{
delete[] Data;
}
Map& operator = (const Map& copyFrom)
{
// 0) delete the old one!
delete[] Data;
// 1) copy Size and Capacity
Size = copyFrom.Size;
Capacity = copyFrom.Capacity;
// 2) Allocate Memory
Map* Data = new Map[Capacity];
// 3) Copy the Map Elements
for(int i = 0; i<Size; i++)
Data[i] = copyFrom.Data[i];
return *this;
}
// Index Operator
VALUE_TYPE& operator[] (KEY_TYPE key) const
{
return Data[key];
}
// Accessor functions: read-only access to Size and Capacity
int GetSize() const //const does not modify ANY data members of the class (size, capacity, or data)
{
return Size;
}
int GetCapacity() const
{
return Capacity;
}
void PushBack(const VALUE_TYPE& newElement) //adds value to end of Map as default
{
if(Size >= Capacity)
increaseCapacity(2 * Capacity);
Data[Size] = newElement;
Size++; // increases size of the array so it can be used later.
}
// Overloaded Add function, inserts a value at specified index, calls in "Insert" to do so.
void Add(const VALUE_TYPE& newElement, int index)
{
if( (index<0) || (index > Size))
{
throw ("Index to insert is out of range");
}
//Make sure there's space!
if (Size >= Capacity)
increaseCapacity(2*Capacity); //increase size of array if too small!
Insert(index, newElement);
}
void Remove(int index) // index = index to be removed.
{
// Make sure it's inside the bounds
if( (index<0) || (index > Size))
{
throw ("Index to Remove is out of range.");
}
// it's going to remove the unneeded space by having its capacity one above the Size.
Map* new_Data = new Map[Size];
//Copy data onto new pointer section.
for(int x = 0; x<Size; x++)
new_Data[x] = Data[x];
delete[] Data; //deallocates old memory and uneeded capacity slots.
for(int x = index; x < (Size - 1); x++) //removes the value at index 'index.' Now Data has a capacity of the amount of slots used and one more for a NULL value.
new_Data[x] = new_Data[x+1];
Data = new_Data;
Data[Size-1] = NULL;
Size--;
}
void increaseCapacity(int new_capacity)
{
if(new_capacity>Capacity)
{
if(new_capacity> 2* Capacity)
Capacity = new_capacity;
else
Capacity *= 2;
//create Map with a new capacity!
Map* new_Map = new Map[Capacity];
for(int x = 0; x<Size; x++)
{
new_Map[x] = Data[x];
}
//clear out old memory
delete[] Data;
//set data pointer to the new Map
Data = new_Map;
}
}
KEY_TYPE * Key; // Used to identify mapped values.
VALUE_TYPE MappedValue; // The value actually contained.
private:
int Size; // The count of actual C-Array elements used
int Capacity; // The count of C-array elements allocated
// The encapsulated C-array
VALUE_TYPE * Data; // pointer of type 'DATA_TYPE' called data (will be name of our array).
void Insert(const int index, const VALUE_TYPE& insertValue)
{
if( (index<0) || (index > Size))
{
throw out_of_range ("Index to insert is out of range");
}
//Time to shuffle the array down!
for(int x = Size; x>index; x--)
{
Data[x] = Data[x-1];
}
//Insert the new item at index 'Index!'
Data[index] = insertValue;
Size++;
}
};
SubdomainPart.h
// SubdomainPart.h - SubdomainPart validation class declaration
// Written by -------
#pragma once
#include "String.h"
using namespace std;
class SubdomainPart
{
public:
// Takes the address and stores into the Address data member
SubdomainPart(const String& address);
// Returns true when the Address is valid or false otherwise
virtual bool IsValid();
private:
String Address;
};
SubdomainPart.cpp
// SubdomainPart.cpp - Subdomain validation class implementation
// Written by ---------
#pragma once
#include "SubdomainPart.h"
// Takes the address and stores into the Address data member
SubdomainPart::SubdomainPart(const String& address)
{
Address = address;
}
// Returns true when the Address is valid or false otherwise
bool SubdomainPart::IsValid()
{
int currentDotIndex = 0;
int nextDotIndex = 0;
int found = 0; // first index of a found invalid character
int hyphenIndex = 0; // used to check hyphen rule
// 1. Check the size, 255 total characters
if(Address.GetLength() < 1 || Address.GetLength() > 255)
return false;
// Checks for valid amount of 1-63 characters between dots
currentDotIndex = Address.FindFirstOf('.');
if(currentDotIndex == 0 || currentDotIndex == Address.GetLength()-1)
return false;
else if(currentDotIndex!=(-1))
nextDotIndex = Address.Find('.', currentDotIndex+1);
else
nextDotIndex = (-1); // if no '.' is found, ensures the following loop doesn't run.
while(nextDotIndex!=(-1))
{
if((nextDotIndex-currentDotIndex) == 1 || (nextDotIndex-currentDotIndex) > 63)
return false;
currentDotIndex = nextDotIndex;
nextDotIndex = Address.Find('.', currentDotIndex+1);
}
// 2. Check for valid characters
found = Address.FindFirstNotOf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-.");
if(found!=(-1)) // if a character not listed above is found.
return false;
// 3. Check for dash rule
// Making sure hyphens aren't located at the first or last index of a subdomain.
hyphenIndex = Address.FindFirstOf('-');
if(hyphenIndex == 0)
return false;
hyphenIndex = Address.FindLastOf('-');
if(hyphenIndex == Address.GetLength()-1)
return false;
// Makes sure two hyphens aren't in a row.
for(int x = 1; x<Address.GetLength(); x++)
if(Address[x] == '-' && Address[x] == Address[x-1])
return false;
return true;
}
I don't see a default constructor in this class:
class SubdomainPart
{
public:
// Takes the address and stores into the Address data member
SubdomainPart(const String& address);
// Returns true when the Address is valid or false otherwise
virtual bool IsValid();
private:
String Address;
};
Keep in mind that this map constructor is default-constructing every member rather than initializing them:
Map(int initialCapacity = 10)
{
Size = 0;
Capacity = initialCapacity;
Key;
MappedValue;
//Allocate the C-Array elements using HEAP
Data = new VALUE_TYPE[Capacity];
}
You don't have a default constructor for SubdomainPart you have only provided a copy constructor. A default constructor takes no argument.
The compiler is complaining that SubdomainPart doesn't have a default constructor, and indeed it doesn't. It's required because your Map contains an object of type VALUE_TYPE:
VALUE_TYPE MappedValue;
Also, your Map constructor contains very weird code. I assume you actually wanted to use an initialiser list:
Map(int initialCapacity = 10)
: Key()
, MappedValue()
, Size(0)
, Capacity(initialCapacity)
, Data(new VALUE_TYPE[Capacity])
{}
The problem is with Data = new VALUE_TYPE[Capacity]; part.
The compiler generates code to allocate the array and instantiate each element by calling the parameterless constructor for VALUE_TYPE. As SubdomainPart doesn't have one (since you have defined a custom one), the compiler throws an error.
The reason that compiler reports error in map.h is that it is exactly the place where the constructor is called from. It is not used in SubdomainPart code, it is just defined there.