Search code examples
c++vectorstructpush-back

C++ Multiple Struct Vectors Error


I am trying to make two different vectors containing custom structures but when I try to add elements to the vectors it works for the "deck" vector but throws an error of the "players" vector. I am new to C++ and cannot figure out what is wrong.

These are the errors it throws:

warning: extended initializer lists only available with -std=c++11 or -std=gnu++11|

error: no matching function for call to 'std::vector<BlackjackClass::player>::push_back(<brace-enclosed initializer list>)'|

This is the code I am using:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class BlackjackClass {

    private:
        struct card
        {
                string label;
                int value;
                string suit;
        };
        vector<card> deck;

        struct player
        {
                string name;
                int bankroll;
                int default_bet = 5;
        };
        vector<player> players;

    public:
        BlackjackClass()
        {
            // Works
            deck.push_back({"Queen", 10, "Hearts"});
            // Doesn't Work
            players.push_back({"Jim", 500, 5});

        }
};

int main()
{
    BlackjackClass Blackjack;
}

Solution

  • It is because you have a default value for default_bet. Remove it and it will work or build the object explicitely instead of initializer list

        struct player
        {
                string name;
                int bankroll;
                int default_bet = 5;
                player(string name_, int bankroll_, int default_bet_)
                {
                    name=name_;
                    bankroll=bankroll_;
                    default_bet_=default_bet_;
                }
        };
    
    
        players.push_back(player("Jim", 500, 5));