3

I'm working on a Boggle game solver that would read lines of a text file (the board).

I've been going back and forth if I should use a vector of strings or a vector matrix of chars. I'm thinking the vector of chars would be easier to access as it would be myvec[y][x] where the vector of strings would require me to use the string.at() function.

I don't know which would have a better performance if I should parse each line in to the chars or leave the line as a string and access each char as needed. Any suggestions on which one I should do? Explaining why would be helpful.

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
krizzo
  • 1,823
  • 5
  • 30
  • 52
  • 4
    You can use `[]` with strings too. `at` provides out-of-bounds checking. – chris May 08 '12 at 01:44
  • @chris Oh never tried that with strings. Ok well that pretty much solved my question since a vector of strings will be easier. Thanks. – krizzo May 08 '12 at 01:46
  • 2
    Strings are much better than char arrays. Always choose them if you can. Just so you know, the syntax is possible through the string class overloading `operator[]`. – chris May 08 '12 at 01:48
  • @chris: While that is *generally* good advice, why would it be better for a Boggle game rather than a (essentially) a 2-d array of `char` where you're unlikely to be treating a row as a `string`? – johnsyweb May 08 '12 at 01:53
  • @LF4: The best advice I can offer is to **start coding** with one or the other. If you have issues (performance, readability, maintainability, *etc*...) **then** switch. – johnsyweb May 08 '12 at 01:55
  • 1
    @Johnsyweb, oops I missed the boggle part! Indeed a character array definitely works better for something like that. The question title is a bit misleading there. Strings should always be chosen if the sequence of characters has some meaning to it. – chris May 08 '12 at 02:09
  • @chris: It looks like you were not the only one to read the title but miss the first sentence of the actual question! – johnsyweb May 08 '12 at 03:48

1 Answers1

4

As commented, you can use operator[] on strings just like vectors or arrays.

Under proper optimisation, the performace will be about the same for vector<char> as for string - both are arrays under the hood, and in both cases operator[] will effectively be a structure member access and an indirect lookup. They even provide almost the same set of methods.

Choose whichever makes your code more readable/simple.

Michael Slade
  • 13,802
  • 2
  • 39
  • 44