Question

Data Structures and Algorithms C++: I'm having a hard time getting my main.cpp part of the...

Data Structures and Algorithms C++:

I'm having a hard time getting my main.cpp part of the source code (shown below) to output the following:

Inserting elements to array list:
The list contains
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

Deleting elements:

The list contains:

2 4 6 8 10 12 14 16 18 20 22 24

this is a programming problem in chapter 9 (exercise 3) from the Data Abstraction and Problem Solving with C++ (7th Edition).

Any suggestion are highly appreciated! :)

SOURCE CODE:

main.cpp

#include "MyArrayList.cpp"
#include
#include
using namespace std;

// Method to display the listPtr.
void displayMyList(MyArrayList* lstPtr)
{
   // Display message.
   cout << "The list contains " << endl;
   // Use loop to display all the elements.
   for (int pp = 1; pp <= lstPtr->getListCurrentSize(); pp++)
   {
       // display the current element
       cout << lstPtr->getItemByPos(pp) << " ";
   }
   // output new line.
   cout << endl;
}

// main()
int main()
{
   // Create array list.
   MyArrayList mylist;

   // Display message.
   cout<<"Inserting elements to array list: ";
   // Declare string array of data.
   string data1[] = {"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"};
  
   // Use loop to insert elements.
   for(int kk=0;kk<25;kk++)
   {
       // Call addListElement().
       mylist.addListElement(kk+1,data1[kk]);
       // Call displayMyList().
       displayMyList(&mylist);
       // Display message.
   }
   cout<<"\n\nDeleting elements:"<< endl;
      
   // Use loop to delete elements.
   for(int kk=1;kk<=15;kk++)
   {
       // Call deleteByPos().
       mylist.deleteByPos(kk);
       // Call displayMyList().
       displayMyList(&mylist);
       // Pause output.
       system("pause");
       // Stop.
       return 0;
   }
}

MyArrayList.cpp

// Implementation code for the class MyArrayList.
#include "MyArrayList.h"

// Constructor to set the aryItemCnt and maxItemCap to default values.
template
MyArrayList::MyArrayList()
{
   // Set aryItemCnt to 0.
   aryItemCnt = 0;
   // Set maxItemCap to 0.
   maxItemCap = 5;
   // Allocate memory.
   arrayItems = new ItemType[maxItemCap];
}

// Method outputs true if the list is clear.
template
bool MyArrayList::checkEmpty() const
{
   // Check condition and return the result.
   return aryItemCnt == 0;
}

// Method outputs the number of elements in the list.
template
int MyArrayList::getListCurrentSize() const
{
   // Return the aryItemCnt value.
   return aryItemCnt;
}

// Method outputs true if the newItem is added to the list at newPos.
template
bool MyArrayList::addListElement(int newPos, const ItemType& newItem)
{
   // Check array is full.
   if(aryItemCnt == maxItemCap)
   {
       // On condition success, expand the size.
       expandCapacity();
   }
   // Check newPos is valid.
   bool canAdd = (newPos >= 1) && (newPos <= aryItemCnt + 1);
   // If newPos is valid.
   if (canAdd)
   {
       // Use loop to make space for newItem.
       for (int pp = aryItemCnt; pp >= newPos; pp--)
       {
           // Move elements towards array end.
           arrayItems[pp] = arrayItems[pp - 1];
           // Place the newItem at newPos.
           arrayItems[newPos - 1] = newItem;
           // Increase the aryItemCnt by 1.
           aryItemCnt++;
       }
   }
   // return the canAdd.
   return canAdd;
}

// Method outputs true if element at elementPos is deleted from the list.
template
bool MyArrayList::deleteByPos(int elementPos)
{
   // Check elementPos is valid.
   bool canDelete = (elementPos >= 1) && (elementPos <= aryItemCnt);
   // If elementPos is valid,
   if (canDelete)
   {
       // Use loop to remove element at elementPos.
       for (int aa = elementPos, bb = aa - 1; aa < aryItemCnt; aa++, bb++)
       // Move elements towards array beginning.
       arrayItems[bb] = arrayItems[aa];
       // Decrease the aryItemCnt value by 1.
       aryItemCnt--;
       // Check condition.
       if(maxItemCap>20 && aryItemCnt<(maxItemCap/2))
       // Call reduceCapacity().
       reduceCapacity();
   }
   // Return the canDelete.
   return canDelete;
}

// Method removes all the elements in the list.
template
void MyArrayList::clearList()
{
   // Set aryItemCnt to 0.
   aryItemCnt = 0;
}

// Method outputs item at the elementPos.
template
ItemType MyArrayList::getItemByPos(int elementPos) const
{
   //check if elementPos is valid.
   bool canGet = (elementPos >= 1) && (elementPos <= aryItemCnt);
   // If elementPos is valid,
   if (canGet)
   {
       // Return the item at the elementPos.
       return arrayItems[elementPos - 1];
   }
   // If elementPos is not valid,
   else
   {
       // Throw the exception.
       throw std::invalid_argument("Element Position is not valid.");
   }
}

// Method sets the newItem at the given elementPos.
template
void MyArrayList::setItemByPos(int elementPos, const ItemType& newItem)
{
   // Check elementPos is valid.
   bool canSet = (elementPos >= 1) && (elementPos <= aryItemCnt);
   // If elementPos is valid,
   if (canSet)
   // Set the newItem at elementPos.
   arrayItems[elementPos - 1] = newItem;
   // If elementPos is not valid,
   else
   {
       // Throw the exception.
       throw std::invalid_argument("Element Position is not valid.");
   }
}

// Method that expands the array.
template
void MyArrayList::expandCapacity()
{
   // Double the maxItemCap.
   maxItemCap = 2 * maxItemCap;
   // create tp.
   ItemType *tp = new ItemType[maxItemCap];
   // use loop to copy the array items.
   for (int kk = 0; kk < aryItemCnt; kk++)
   {
       // Copy the current item.
       tp[kk]=arrayItems[kk];
       // Delete arrayItems.
       delete[] arrayItems;
       // Update the arrayItems.
       arrayItems = tp;
   }
}

// Method to reduce the array size.
template
void MyArrayList::reduceCapacity()
{
   // Reduce the maxItemCap.
   maxItemCap = 3 * (maxItemCap/4);
   // Create tp.
   ItemType *tp = new ItemType[maxItemCap];
   // Use loop to copy the array items.
   for(int kk = 0; kk < aryItemCnt; kk++)
   {
       // Copy the current item.
       tp[kk]=arrayItems[kk];
       // Delete arrayItems.
       delete[] arrayItems;
       // Update the arrayItems.
       arrayItems = tp;
   }
}

MyArrayList.h

#ifndef MYARRAYLIST_H
#define MYARRAYLIST_H
#include "MyArrayListInterface.h"
#include "stdexcept"

// declare class MyArrayList
template
class MyArrayList : public MyArrayListInterface
{
private:
   // this itemtype function declares an array of ItemType.
   ItemType *arrayItems;
   // this int function declares aryItemCnt (array item count).
   int aryItemCnt;
   // this int function declares maxItemCap (maximum item capacity).
   int maxItemCap;
   // this void function expands the array.
   void expandCapacity();
   // this void function reduces the array size.
   void reduceCapacity();

public:
   // this is our default constructor.
   MyArrayList();
   // this boolean function outputs true if the list is clear.
   bool checkEmpty() const;
   // this int function outputs the number of elements in the list.
   int getListCurrentSize() const;
   // this boolean function outputs true if the newItem is added to the list at newPos.
   bool addListElement( int newPos, const ItemType& newItem);
   // this boolean function outputs true if element at position is deleted from the list.
   bool deleteByPos( int elementPos);
   // this void function removes all the elements in the list.
   void clearList();
   // this class itemtype function outputs item at the position.
   ItemType getItemByPos( int elementPos) const;
   // this void function sets the newItem at the given position.
   void setItemByPos( int elementPos, const ItemType& newItem);

   // End of MyArrayList.
};

#endif

MyArrayListInterface.h

#ifndef MYARRAYLISTINTERFACE_H
#define MYARRAYLISTINTERFACE_H

// declare class MyArrayListInterface
template
class MyArrayListInterface
{
public:
   //this boolean function outputs true if the list is clear.
   bool checkEmpty() const;
   //this int function outputs the number of elements in the list.
   int getListCurrentSize() const;
   //this boolean function outputs true if the newItem is added to the list at newPos.
   bool addListElement( int newPos, const ItemType& newItem);
   //this boolean function outputs true if element at position is deleted from the list.
   bool deleteByPos( int elementPos);
   //this void function removes/clears all the elements in the list.
   void clearList();
   //this class type function outputs item at the position.
   ItemType getItemByPos( int elementPos) const;
   //this void function sets the newItem at the given position.
   void setItemByPos( int elementPos, const ItemType& newItem);

   // End of MyArrayListInterface.
};

#endif

0 0
Add a comment Improve this question Transcribed image text
Answer #1

First you don't need MyArrayListInterface to be base class of MyArrayList class. you are duplicating all the public functions so interface is useless.

Second you have problem in every for loop. see my code how to end { }. you also need to provide template argument for class functions.

see the changes i made in code and compare with previous code. if you still have any problem or doubt, let me know. thank you.

====================================

MyArrayList .h

====================================

#ifndef MYARRAYLIST_H
#define MYARRAYLIST_H
#include "stdexcept"

// declare class MyArrayList
template <typename ItemType>
class MyArrayList
{
private:
   // this itemtype function declares an array of ItemType.
   ItemType* arrayItems;
   // this int function declares aryItemCnt (array item count).
   int aryItemCnt;
   // this int function declares maxItemCap (maximum item capacity).
   int maxItemCap;
   // this void function expands the array.
   void expandCapacity();
   // this void function reduces the array size.
   void reduceCapacity();

public:
   // this is our default constructor.
   MyArrayList();
   // this boolean function outputs true if the list is clear.
   bool checkEmpty() const;
   // this int function outputs the number of elements in the list.
   int getListCurrentSize() const;
   // this boolean function outputs true if the newItem is added to the list at newPos.
   bool addListElement(int newPos, const ItemType& newItem);
   // this boolean function outputs true if element at position is deleted from the list.
   bool deleteByPos(int elementPos);
   // this void function removes all the elements in the list.
   void clearList();
   // this class itemtype function outputs item at the position.
   ItemType getItemByPos(int elementPos) const;
   // this void function sets the newItem at the given position.
   void setItemByPos(int elementPos, const ItemType& newItem);

   // End of MyArrayList.
};

#endif

===================================

MyArrayList .cpp

===================================

// Implementation code for the class MyArrayList.
#include "MyArrayList.h"
#include <iostream>
using namespace std;

// Constructor to set the aryItemCnt and maxItemCap to default values.
template <typename ItemType>
MyArrayList<ItemType>::MyArrayList()
{
   // Set aryItemCnt to 0.
   aryItemCnt = 0;
   // Set maxItemCap to 0.
   maxItemCap = 5;
   // Allocate memory.
   arrayItems = new ItemType[maxItemCap];
}

// Method outputs true if the list is clear.
template <typename ItemType>
bool MyArrayList<ItemType>::checkEmpty() const
{
   // Check condition and return the result.
   return aryItemCnt == 0;
}

// Method outputs the number of elements in the list.
template <typename ItemType>
int MyArrayList<ItemType>::getListCurrentSize() const
{
   // Return the aryItemCnt value.
   return aryItemCnt;
}

// Method outputs true if the newItem is added to the list at newPos.
template <typename ItemType>
bool MyArrayList<ItemType>::addListElement(int newPos, const ItemType& newItem)
{
   // Check array is full.
   if (aryItemCnt == maxItemCap)
   {
       // On condition success, expand the size.
       expandCapacity();
   }
   // Check newPos is valid.
   bool canAdd = (newPos >= 1) && (newPos <= (aryItemCnt + 1));
   // If newPos is valid.
   if (canAdd)
   {
       // Use loop to make space for newItem.
       for (int pp = aryItemCnt; pp >= newPos; pp--)
       {
           // Move elements towards array end.
           arrayItems[pp] = arrayItems[pp - 1];
       }
       // Place the newItem at newPos.
       arrayItems[newPos - 1] = newItem;
       // Increase the aryItemCnt by 1.
       aryItemCnt++;
   }
   // return the canAdd.
   return canAdd;
}

// Method outputs true if element at elementPos is deleted from the list.
template <typename ItemType>
bool MyArrayList<ItemType>::deleteByPos(int elementPos)
{
   // Check elementPos is valid.
   bool canDelete = (elementPos >= 1) && (elementPos <= aryItemCnt);
   // If elementPos is valid,
   if (canDelete)
   {
       // Use loop to remove element at elementPos.
       for (int aa = elementPos, bb = aa - 1; aa < aryItemCnt; aa++, bb++)
           // Move elements towards array beginning.
           arrayItems[bb] = arrayItems[aa];
       // Decrease the aryItemCnt value by 1.
       aryItemCnt--;
       // Check condition.
       if (maxItemCap > 20 && aryItemCnt < (maxItemCap / 2))
           // Call reduceCapacity().
           reduceCapacity();
   }
   // Return the canDelete.
   return canDelete;
}

// Method removes all the elements in the list.
template <typename ItemType>
void MyArrayList<ItemType>::clearList()
{
   // Set aryItemCnt to 0.
   aryItemCnt = 0;
}

// Method outputs item at the elementPos.
template <typename ItemType>
ItemType MyArrayList<ItemType>::getItemByPos(int elementPos) const
{
   //check if elementPos is valid.
   bool canGet = (elementPos >= 1) && (elementPos <= aryItemCnt);
   // If elementPos is valid,
   if (canGet)
   {
       // Return the item at the elementPos.
       return arrayItems[elementPos - 1];
   }
   // If elementPos is not valid,
   else
   {
       // Throw the exception.
       throw std::invalid_argument("Element Position is not valid.");
   }
}

// Method sets the newItem at the given elementPos.
template <typename ItemType>
void MyArrayList<ItemType>::setItemByPos(int elementPos, const ItemType& newItem)
{
   // Check elementPos is valid.
   bool canSet = (elementPos >= 1) && (elementPos <= aryItemCnt);
   // If elementPos is valid,
   if (canSet)
       // Set the newItem at elementPos.
       arrayItems[elementPos - 1] = newItem;
   // If elementPos is not valid,
   else
   {
       // Throw the exception.
       throw std::invalid_argument("Element Position is not valid.");
   }
}

// Method that expands the array.
template <typename ItemType>
void MyArrayList<ItemType>::expandCapacity()
{
   // Double the maxItemCap.
   maxItemCap = 2 * maxItemCap;
   // create tp.
   ItemType* tp = new ItemType[maxItemCap];
   // use loop to copy the array items.
   for (int kk = 0; kk < aryItemCnt; kk++)
   {
       // Copy the current item.
       tp[kk] = arrayItems[kk];
   }
   // Delete arrayItems.
   delete[] arrayItems;
   // Update the arrayItems.
   arrayItems = tp;
}

// Method to reduce the array size.
template <typename ItemType>
void MyArrayList<ItemType>::reduceCapacity()
{
   // Reduce the maxItemCap.
   maxItemCap = 3 * (maxItemCap / 4);
   // Create tp.
   ItemType* tp = new ItemType[maxItemCap];
   // Use loop to copy the array items.
   for (int kk = 0; kk < aryItemCnt; kk++)
   {
       // Copy the current item.
       tp[kk] = arrayItems[kk];
   }
   // Delete arrayItems.
   delete[] arrayItems;
   // Update the arrayItems.
   arrayItems = tp;
}

===================================

main.cpp

===================================

#include "MyArrayList.cpp"
#include <iostream>
using namespace std;

// Method to display the listPtr.
template <typename ItemType>
void displayMyList(MyArrayList<ItemType>* lstPtr)
{
   // Display message.
   cout << "The list contains " << endl;
   // Use loop to display all the elements.
   for (int pp = 1; pp <= lstPtr->getListCurrentSize(); pp++)
   {
       // display the current element
       cout << lstPtr->getItemByPos(pp) << " ";
   }
   // output new line.
   cout << endl;
}

// main()
int main()
{
   // Create array list.
   MyArrayList<int> mylist;

   // Display message.
   cout << "Inserting elements to array list: ";
  
   // Use loop to insert elements.
   for (int kk = 0; kk < 25; kk++)
   {
       // Call addListElement().
       mylist.addListElement(kk + 1, kk + 1);
   }
   // Call displayMyList().
   displayMyList(&mylist);
  
   // Display message.
   cout << "\n\nDeleting elements:" << endl;

   // Use loop to delete elements.
   for (int kk = 1; kk <= 15; kk++)
   {
       // Call deleteByPos().
       mylist.deleteByPos(kk);
   }
   // Call displayMyList().
   displayMyList(&mylist);
   // Pause output.
   system("pause");
   // Stop.
  
   return 0;
}

Add a comment
Know the answer?
Add Answer to:
Data Structures and Algorithms C++: I'm having a hard time getting my main.cpp part of the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ Error. I'm having trouble with a pointer. I keep getting the error "Thread 1: EXC_BAD_ACCESS...

    C++ Error. I'm having trouble with a pointer. I keep getting the error "Thread 1: EXC_BAD_ACCESS (code=1, address=0x18)" The objective of the assignment is to revise the public method add in class template LinkedBag so that the new node is inserted at the end of the linked chain instead of at the beginning. This is the code I have: linkedBag-driver.cpp BagInterface.hpp LinkedBag.hpp Node.hpp int main) LinkedBag<string> bag; cout << "Testing array-based Set:" << endl; cout << "The initial bag is...

  • (C++) Two stacks of the same type are the same if they have the same number...

    (C++) Two stacks of the same type are the same if they have the same number of elements and their elements at the corresponding positions are the same. Overload the relational operator == for the class stackType that returns true if two stacks of the same type are the same; it returns false otherwise. Also, write the definition of the function template to overload this operator. Write a program to test the various overloaded operators and functions of classstackType. **Please...

  • Given an array-based stack of integers, sort it largest to smallest using recursion. Do NOT use...

    Given an array-based stack of integers, sort it largest to smallest using recursion. Do NOT use any loop constructs such as while, for and so on. Only use the following stack ADT functions in the recursion: IsEmpty Push Pop Top (note: doesn’t remove anything from the stack). Your program should read 10 integers into a stack from a file named input.txt (outputting them to the screen first) then implement the recursions. Use stacks only, no queues. The program should then...

  • This project is divided into 3 parts: Part 1. Create a new project and download the arrayList and...

    This project is divided into 3 parts: Part 1. Create a new project and download the arrayList and unorderedArrayList templates that are attached. Create a header file for your unorderedSet template and add it to the project. An implementation file will not be needed since the the new class will be a template. Override the definitions of insertAt, insertEnd, and replaceAt in the unorderedSet template definition. Implement the template member functions so that all they do is verify that the...

  • Double linked list implementation of PutItem function. How to fix my code to get desired output b...

    Double linked list implementation of PutItem function. How to fix my code to get desired output below: Output: 2 5 8 #ifndef ITEMTYPE_H #define ITEMTYPE_H enum RelationType { LESS, GREATER, EQUAL}; class ItemType { public:     ItemType();     void setValue(int newValue);     int getValue() const;     RelationType ComparedTo(ItemType newItem); private:     int value; }; #endif // ITEMTYPE_H // ItemType.cpp #include "ItemType.h" ItemType::ItemType() {     value = 0; } void ItemType::setValue(int newValue) {     value = newValue; } int ItemType::getValue() const {     return value; } RelationType ItemType::ComparedTo(ItemType newItem)...

  • 5. Below i s the class deciaration for the Bag class from your text. Refer to...

    5. Below i s the class deciaration for the Bag class from your text. Refer to this hea he Ted implementation @file Bag.h #ifndet BAG #define BAG template <class ItemType> class Bag private: static const int DEFAULT BAG SIZE 6; Il current count of Bag items /I max capacity of the Bag ItemType items[DEFAULT BAG SIZE]; //array of Bag items int itemCount; int maxitems; /l Returns either the index of the element in the array items that ll contains the...

  • Use C++! This program uses the class myStack to determine the highest GPA from a list of students with their GPA.The program also outputs the names of the students who received the highest GPA. Redo t...

    Use C++! This program uses the class myStack to determine the highest GPA from a list of students with their GPA.The program also outputs the names of the students who received the highest GPA. Redo this program so that it uses the STL list and STL queue! Thank you! HighestGPAData.txt* 3.4 Randy 3.2 Kathy 2.5 Colt 3.4 Tom 3.8 Ron 3.8 Mickey 3.6 Peter 3.5 Donald 3.8 Cindy 3.7 Dome 3.9 Andy 3.8 Fox 3.9 Minnie 2.7 Gilda 3.9 Vinay...

  • C++. Difficulty with quickSort function. Code will not run quickSort function. The code I'm having trouble...

    C++. Difficulty with quickSort function. Code will not run quickSort function. The code I'm having trouble with is in bold. -------------------------------------------------------------------------------------------------driverProgram.cpp #include #include #include #include #include "quickSort.cpp" using namespace std; int main() { const int MIN_SIZE = 4; //Array size const int SIZE = 25; int theArray[SIZE] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 12, 13, 14, 15, 16, 17, 18, 19, 18, 19, 20, 21, 22, 23, 24, 25}; cout << "List of 25 items: ";...

  • I want the full code for this part and Its needs to be done in C++...

    I want the full code for this part and Its needs to be done in C++ Use a linked list to implement the following skeleton of an unsorted list typedef int ItemType: struct NodeType ItemType item; NodeType "next; class List List(); // default constructor List( const List &x); I copy constructor: deep copy is required List & operator = (const List &x); // assignment operator: deep copy. 1s required bool IsThere(ItemType x); identify if x is in the list void...

  • I'm just not sure how to tackle all the template class this header wants me to...

    I'm just not sure how to tackle all the template class this header wants me to write. I got this far into making the template for public and private and would like help on the template functions. Thank you! This is in C++ by the way. #include <iostream> #include <cassert> using namespace std; #ifndef ARRAYLIST_H #define ARRAYLIST_H template<typename T> class arrayList { public:    arrayList(); //Constructor with default parameter. //Sets maxSize = 100 and length = 0 if no parameter...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT