C++ 2-dimensional Vectors

Hey guys,

I’ve just come across something I don’t remember from learning Vectors – how to make a 2-dimensional STL Vector. Basically, height and width will be changing each time the program is run (the array will be filled with char’s). My first idea was to do a simple char array via char the2d[width][height], but C++ demands that width and height be constants. I’ve never really worked with character arrays before, so I then tried a STL Vector.

But the only thing I can’t figure out is how to declare a 2-dimensional Vector. Is this even possible with the STL? Or do I need to declare a vector of vector of chars? If so, how do I then access elements, syntaxically?

Or is there a simple workaround – resizing a character array?

Let me know if I’m making no sense. Thanks guys. :smiley:

vector< vector<yourtypehere> >

The spaces are important. Try it without and you’ll see why.

Yeah, but I mean, how do I reference a value in this – what’s the syntax?

Just like you would a 2d array, or you can use the at() function.

d’oh-- gotcha. Works fine. Thanks. :smiley:

One more question for any guru still reading this far-- is there a C++ equivalent of the VB “on error resume next”?

No, although depending on your platform you might be able to tell the OS not to break on certain kinds of exceptions.

Actually, that’s not entirely true, depending on what you mean by “equivalent.” You could get the same functionality by wrapping every statement in its own try block, which could work for small bits of code.

But even in VB, all of the “On Error” statements break structuredness and are considered bad form, although I’ll admit that Resume Next is the least goto-like.

Even so, you’re acknowledging that an error occured (basically some statement didn’t run to completion), and that you don’t care. It’s unlikely you could design any significant amount of code so that ANY one statement could fail. A better solution is to put a try/catch block (with an empty catch if you like) around the SPECIFIC statement that CAN fail “harmlessly.” (Which is why .NET depecates the OnError mechanisms in favor of structured exception handling.)