I have been working on creating an RPG combat sim for code-practice. A single ‘battle’ constitutes a 3D vector based on number of rounds,number of fighter and number of Rolls (per fighter in each round) in that order. After hours of searching I have put together this code. I am aware there are easier ways to accomplish this (boost / matrix etc..) but I want to finish this and learn where my STL::vector manipulation is going wrong
#include <vector>
#include <algorithm>
using namespace std;
class Combat{
private:
int numberOfRounds;
int numberOfCombatants;
int numberOfRolls;
int sidesDie;
vector <vector <vector <int> > > result;
public:
void printMenu();
void battle();
void printResult();
int roll(int die);
};
int Combat::roll(int die)
{
die=sidesDie;
srand(time(0));
int r=(1+rand()%die);
return r;
void Combat::battle(){
cout<<setw(10)<<" Computing results of battle ...\n";
int i,j,k;
for (i=0;i<numberOfRounds;++i){
cout<<"Round number "<<i+1;
for(j=0;j<numberOfCombatants;++j){
for(k=0;k<numberOfRolls;++k){
result[i][j].push_back(roll(sidesDie));
}
cout<<endl;
}
cout<<endl;
}
}
The code above is supposed to create a 3D vector ‘result’ which should store dice-rolls inside cells per player per round. It crashes during execution without showing an error. i suspect the bug is in the way i am storing values inside the 3d vector
You are correct – your result variable is a vector of vector of vector of ints. In your battle loop, you are attempting to push_back into the innermost vector, but the outer two vectors don’t have any contents defined yet.
You’ll need to push_back an entry for i and j as well (of the appropriate subtype, e.g. vector < vector < int > >, and then vector < int >, to use the vector in this fashion.
edit
For instance: