Dynamically creating objects in a vectorC++

87 Views Asked by At

I am trying to dynamically populate a vector with objects from a single class. I am encountering two problems.

  1. Being able to identify objects in the vector when I need to reference them.

  2. My current code cuts off the last element.

I stepped through this function in the debugger and discovered that element '0' in the vector has character_name= "" and then the user input starts at element '1'. For example, if I type "Bilbo Baggins", the element 1 character_name is set to that rather than element 0. The final character name entered by the user never gets added to the vector; variable player_name gets set to whatever the user inputs, but apparently party.push_back(player); does not happen afterwards, at least not correctly. The size outputs correctly and is equal to how many names are entered.

What can I do to add objects to the vector correctly and not cut off the last entry or start from index 0? Does it have something to do with how push_back works?

What is the best way to reference objects that all have the same name and can I change their names after they are defined? Can I reference an object by one of its members?

The for loops at the bottom are there for debugging. The map is there in an attempt to solve my first problem, but referencing objects by user input seems problematic. main() only includes initialize_party(); and return 0;. Let me know if I need to add my main.h or my class definitions.

#include "main.h"
vector<Character> party;
map<string, Character> party_map;

void initialize_party(void)
{
    int party_members;
    int userSelection;

    cout << "CHARACTER CREATION\n\n";
    cout << "Create Character (1)" << endl;
    cout << "Quit             (0)" << endl;
    cin >> userSelection;
    if (userSelection == 0)
    {
        return;
    }
    else if (userSelection == 1)
    {
        Character player;
        string player_name;
        cout << "Enter character names one at a time and press enter after each one." << endl;
        cout << "Type 'Q' to quit once you are done entering names\n\n" << endl;
        bool looping = true;
        while (looping)
        {
            cout << "Enter character name: ";
            ws(cin);
            getline(cin, player_name);
            if (player_name == "Q")
            {
                break;
            }
            party.push_back(player);
            player.setCharName(player_name);
            party_map[player_name] = player;
        }
    }
    else
    {
        cout << "Invalid Input!" << endl;
    }
    int party_size = party.size();
    for (int i = 0; i < party_size; i++)
    {
        cout << party[i].getCharName() << endl;
    }
    for (Character member : party)
    {
        cout << member.getCharName() << endl;
    }
}
0

There are 0 best solutions below