Io-stream
Io-stream

Reputation: 109

Why does this code no longer work when I swap the array for a vector?

I created a simple "Menu" for an assignment, that would list numbered options that you could select to call functions.

Header file:

#ifndef MENU
#define MENU

#include <string>
#include <vector>

const int MAXCOUNT = 20;

struct menuItem
{
    void(*func) ();
    string descript;

};

class Menu
{
private:
    //menuItem mi[MAXCOUNT];
    vector<menuItem> mi;
    int count;
    void runSelection();
public:
    Menu();
    void addMenu(char *Description, void (*f) ());
    void runMenu();
    void waitKey();
};

#endif

everything was working fine, until I tried to swap out the array of menuItems in the data section so that it would be a vector of menuItems, and all of the sudden it doesn't work. It seems to be stopping in my addMenu function:

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

But I don't understand what changed?

Upvotes: 0

Views: 89

Answers (2)

Galik
Galik

Reputation: 48625

The problem is you are trying to access elements in your vector that have not been created. A std::vector starts out empty and you generally add new elements one by one to the end of the vector increasing its size each time.

Rather like this:

class Menu
{
private:
    vector<menuItem> mi;
    // int count; // no need for this, use mi.size()
    void runSelection();
public:
    Menu();
    void addMenu(char *Description, void (*f) ());
    void runMenu();
    void waitKey();
};

void Menu::addMenu(char *Description, void (*f) (void))
{
    menuItem item = {f, Description};
    mi.push_back(item); // add the new element to the end (back)
}

Upvotes: 0

Jts
Jts

Reputation: 3527

I'm gonna guess that this is your problem

Menu() {
     mi.resize(MAXCOUNT); // you don't have this.
}     
Menu() : mi(MAXCOUNT) { // or this
} 
vector<menuItem> mi { MAXCOUNT} ; // and clearly not this

therefore

if(count < MAXCOUNT)
{
    mi[count].func = f; // this is not valid because mi has a size of 0
    count ++;
}

Here's a way fix your problem (count member not needed anymore):

if (mi.size() < MAXCOUNT)
    mi.push_back({f, Description}); // this would be a fix.

Or resize the vector as explained before.

Upvotes: 3

Related Questions