0

I got my two member functions of class "Gameparty" (I translated all terms for you in english) They use a Gameparty term, which consists of vectors for each Cardgames and Videogames, which are also classes.

The get_minPlayers / get_maxPlayers are getters of their class and give the number of min / max Players for each game. The if part should delete every Cardgame / Videogame which can't be played by the actual number of guests.

Problem: this code produces an error, which shows me that the first for-Loop of Code Sample 1. "calculateBestCardgame()" is using a vector which doesn't exist.

I can avoid this error by reducing numberCardgames-1. Which is strange to me because it works in the 3 other for-Loops The size of temp_Cardgames is 4.

The actual calculation isn't implemented yet but no part of my problem.

Thanks for help!

1.:

    Cardgame Gameparty::calculateBestCardgame(){

    vector <Cardgame> temp_Cardgames = get_availibleCardgames();
    int guests = get_gaesteliste().size();

    int numberCardgames = temp_Cardgames.size();
    for (int i = 0; i < numberCardgames; i++){
        if (temp_Cardgames[i].get_minPlayers() > guests){
            temp_Cardgames.erase(temp_Cardgames.begin() + i);
        }
    }

    numberCardgames = temp_Cardgames.size();
    for (int i = 0; i < numberCardgames; i++){
        if (temp_Cardgames[i].get_maxPlayers() < guests){
            temp_Cardgames.erase(temp_Cardgames.begin() + i);
        }
    }

    Cardgame bestCardgame = temp_Cardgames.back();

    return bestCardgame;
}

2.:

    Videogame Gameparty::calculateBestVideogame(){

    vector <Videogame> temp_Videogames = get_availibleVideogames();
    int guests = get_guestlist().size();

    int numberVideogames = temp_Videogames.size();
    for (int i = 0; i < numberVideogames; i++){
        if (temp_Videogames[i].get_minPlayers() > guests){
            temp_Videogames.erase( temp_Videogames.begin()+i );
        }
    }

    numberVideogames = temp_Videogames.size();
    for (int i = 0; i < numberVideogames; i++){
        if (temp_Videogames[i].get_maxPlayers() < guests){
            temp_Videogames.erase(temp_Videogames.begin() + i);
        }
    }
    Videogame bestVideogame = temp_Videogames.back();

    return bestVideogame;
}
  • 1
    possible duplicate of [Remove elements of a vector inside the loop](http://stackoverflow.com/questions/8628951/remove-elements-of-a-vector-inside-the-loop) – Borgleader Jun 01 '15 at 17:21
  • Firstly, if temp_Cardgames is empty, back() method could cause undefined behavior. See http://www.cplusplus.com/reference/vector/vector/back/. Please change that and update post adding more details about the error. – Emiliano Sangoi Jun 01 '15 at 18:50

0 Answers0