Quote:
|
I have a few questions: Is there any more simple way to do this?
|
Certainly.
Since your vector-of-vectors is always used with a fixed width and height, you can also use a two-dimensional array. There are several ways to do this, like in old-fashioned C (which doesn't allow you to use some of the nice tricks C++ has to offer), by computing your own offsets in a single vector (multiply y by the width and add x), or by using the multiarray container from the excellent Boost library. (
http://www.boost.org/)
My guess is that the second method works best for you. I'll show you how to do this in a "simple" way (simple as in little typing work, not conceptually):
Code:
#include <vector>
#include <algorithm> // for generate ()
#include <iterator> // for ostream_iterator
#include <iostream> // for cout
#include <cstdlib> // for rand ()
using namespace std;
int main (void)
{
const unsigned int size (5);
// Pretend we have a 5 x 5 array by reserving 25 elements.
vector<int> harry (size * size);
// Put some random junk in there.
generate (harry.begin(), harry.end(), rand);
// Copy everything to cout.
copy (harry.begin(), harry.end(),
ostream_iterator<int> (cout, "\n"));
// Show some specific values
cout << "At (2, 3) : " << harry[3 * size + 2] << endl;
cout << "At (1, 4) : " << harry[4 * size + 1] << endl;
return 0;
}
Maybe you prefer writing the for-loops yourself, this code can be tricky to understand right away.
(Of course there's lots of room for improvement; that "y * size + x" belongs in a function, or better yet, a class.)
Quote:
|
I tried cputs(harry[i][k]) and it didn't like that, it says it wants a char *, but I think it should work anyway...
|
Well no, harry[i][k] is an int, and the compiler cannot know how you would like to have it converted to a char *. But this is a problem that you don't have to worry about in C++: cout will do the trick just fine. (You can also do colors I think, but not in an easy way.)
Quote:
|
what is %i? I know, I don't need to know, but I'm curious.
|
The %i is "an integer", and it means that cprintf will substitute the appropriate value before printing it. A quick Google for "printf" or "cprintf" should be enough to find out how to use these functions.
But again, this is C stuff. C++'s cout is easier to use.
Quote:
|
Did you guys hear about the prequil to that matrix? They're going to call it "The Array". And then before that, they're going to have "The Variable".
|
LOL, then I'm surprised the sequel isn't called "The Tensor".
