Question: Hello. I am creating a ring class which has a collection of items ( vector ) that has a reference to a current item in

Hello. I am creating a ring class which has a collection of items (vector) that has a reference to a current item in that vector. I am trying to implement the following operations (methods) within this class. They are:
advance(), which advances the reference to the next object in the list by one, until it gets to the end, when it again references the first object in the vector.
getCurrentItem(), which, when called will get the currently referenced item in the vector.
addItem(), which will add a new item to the vector, increasing its size by 1
removeItem(), which will delete an item from the vector, decreasing its size by 1
-------------------------------------
With my current code, I find that I am able to advance and get the current item as long as I do not add or delete an item, or am not at the end of the vector. If I do add or delete an item, or am at the end of the vector, it gives me a memory allocation error. I am not sure why I am getting this memory allocation error. Can you please help. Many thanks. Below is my current code.
----------------------------------
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class Ring
{
private:
vector m_objectList;
string* pStr = &(m_objectList[0]);
public:
Ring(vector list) : m_objectList(list)
{
}
vector getVector()
{
return m_objectList;
}
void advanceItem()
{
int i =0;
if (i != m_objectList.size()-1)
{
pStr++;
}
else
{
pStr = &(m_objectList[0]);
}
}
string getCurrentItem()
{
return *pStr;
}
void addItem(int index, string addedItem)
{
m_objectList.insert(m_objectList.begin()+ index, addedItem);
}
void removeItem(int index)
{
m_objectList.erase(m_objectList.begin()+ index);
}
};
int main()
{
Ring myList({ "seven", "one", "nine", "twelve" });
cout << myList.getCurrentItem()<< endl;
myList.advanceItem();
cout << myList.getCurrentItem()<< endl;
myList.addItem(2, "three");
cout << myList.getCurrentItem()<< endl;
myList.advanceItem();
myList.advanceItem();
cout << myList.getCurrentItem()<< endl;
myList.advanceItem();
cout << myList.getCurrentItem()<< endl;
myList.advanceItem();
cout << myList.getCurrentItem()<< endl;
for (int i =0; i < myList.getVector().size(); i++)
{
cout << myList.getVector().at(i)<<"";
}
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!