dnun99 dnun99 - 2 months ago 9
C++ Question

How do i completely erase an array and replace it with a vector?

I've been working on this assignment for my class for about a day and I've completed just about everything. The only thing I'm missing is removing my array and replacing it with a vector.

#ifndef MENU
#define MENU
#include <vector>
const int MAXCOUNT = 20;
struct menuItem
{
void(*func)();
char decript[50];
};
class Menu
{
private:
//vector <int> v; i tried replacing the "mi"'s in the menu.cpp file with v.push_back but i kept getting pointer errors
menuItem mi[MAXCOUNT];
int count = 0;
void runSelection();
public:
Menu();
void addMenu(char *Description, void(*f)());
void runMenu();
void waitKey();
};
#endif


This is the cpp file. Im trying to replace the array mi with v. I know im missing something but I can't figure it out so I'm just posting it working with an array.

Menu::Menu()
:count(0)
{

}
void Menu::addMenu(char *Description, void(*f)())
{
if (count < MAXCOUNT)
{
this->mi[count].func = f;
strcpy(this->mi[count].decript, Description);
count++;
}
}
void Menu::runMenu()
{

for (;;)
{
system("CLS");
for (int i = 0; i < count; i++)
{
cout << this->mi[i].decript << endl;

}
runSelection();
}
}
void Menu::waitKey()
{
cout << "Press any key to continue" << endl;
while (!_kbhit());
fflush(stdin);
}
void Menu::runSelection()
{
int select;
cin >> select;
if (select <= count)
this->mi[select - 1].func();

}

Answer

The simplest way should be to replace

    menuItem mi[MAXCOUNT];     

with

   std::vector<menuItem> mi;

and initialize it in your constructor properly

Menu::Menu()
    :count(0)
    ,mi(MAXCOUNT)
{

}

Supposed you had working code before, this should replace the raw array seamlessly.


With the current c++ standard you can even simply use

   std::array<menuItem,MAXCOUNT> mi;

this wouldn't even require initialization in the constructor.