fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Soldier{
  6. public:
  7. Soldier(char c){
  8. type = c;
  9. }
  10. char type;
  11. };
  12.  
  13. int main() {
  14. const int armies = 3;
  15. const int soldiers_in_army = 5;
  16.  
  17. //a 2d vector of armies and its soldiers
  18. vector< vector<Soldier> > *armys = new vector< vector<Soldier> >(armies, vector<Soldier>(soldiers_in_army, Soldier('@')));
  19. //making a pointer array
  20. Soldier **deployment = new Soldier*[armies*soldiers_in_army];
  21. //test if it works
  22. cout << "the third soldier of the second army is of type " << (*armys)[1][2].type << endl;
  23.  
  24. //initializing the pointers of the deployment array to make them point to the Object through the vector.
  25. deployment[1 * (armys->size()) + 2] = &(*armys)[1][2];
  26. cout << "the third soldier of the second army is of type " << deployment[1 * (armys->size()) + 2]->type << endl;
  27. // (*deployment)[1 * (armys->size()) + 2] = (*armys)[1][2];
  28. // cout << "the third soldier of the first army is of type " << (*deployment)[1 * (armys->size()) + 2].type << endl; return 0;
  29.  
  30. // initialize the whole array of pointers
  31. for(int i = 0; i<armys->size(); i++)
  32. for(int j = 0; j<(*armys)[i].size(); j++)
  33. deployment[i *soldiers_in_army + j] = &(*armys)[i][j];
  34.  
  35. // change some values
  36. (*armys)[0][1] = (*armys)[1][1] = (*armys)[2][1] = Soldier('C'); // captain
  37. (*armys)[0][4] = (*armys)[1][3] = (*armys)[2][2] = Soldier('H'); // horsemen
  38.  
  39. // display original
  40. for(int i = 0; i<armys->size(); i++) {
  41. for(int j = 0; j<(*armys)[i].size(); j++)
  42. cout << (*armys)[i][j].type << " ";
  43. cout << endl;
  44. }
  45. // display via pointers
  46. for(int i = 0; i<armies*soldiers_in_army; i++) {
  47. if(i%soldiers_in_army == 0)
  48. cout << endl;
  49. cout << deployment[i]->type << " ";
  50. }
  51.  
  52. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
the third soldier of the second army is of type @
the third soldier of the second army is of type @
@ C @ @ H 
@ C @ H @ 
@ C H @ @ 

@ C @ @ H 
@ C @ H @ 
@ C H @ @