Nested arrays in C++?

I’m working on the Rock Paper Scissors Lizard Spock project, and am too lazy to write out all the conditions. I wanted to create a nested array of ints to tell who kills what, where the proper name of a guess is replaced by an integer. In Javascript, nested arrays are easy:

let defeats = [
  // rock (with an index of 0) defeats scissors (2) and lizard (3)
  [2, 3],
  // paper
  [0, 4],
  // scissors
  [1, 3],
  // lizard
  [1, 4],
  // spock
  [0, 2],

an array like that would make checking the outcome easy:

if(computerGuess == userGuess) {
  std::cout << "draw!\n";
} else if(computerGuess == defeats[userGuess][0] || computerGuess == defeats[userGuess][1]) {
  // if there is something like 'defeats[userGuess].includes(computerGuess)' that would also be helpful
  std::cout << "you win!\n";
} else {
  std::cout << "computer wins!\n";

How could I get this same result with a C++ vector? Or is there a better way?
Thanks :grinning:

I don’t think it’s the only way but int array_name[2][2] = {{0, 1}, {2, 1}}; is the one that springs to mind.

1 Like

Thanks! is the [2][2] necessary for syntax?

For C style arrays I think you’d need something, (you can leave part of it blank and it can intuit the rest), int array_name[][2] = { {0, 1}, {2, 1}} is valid for example but I think [][] fails. Missed your mention of vector the first time around but that has some different options too, see e.g. c++ - Initializing a two dimensional std::vector - Stack Overflow. If you want all the options you’ll need a web search as I just don’t know them well enough.

thanks for clarifying :slightly_smiling_face:

1 Like