vector of vectors again. attempt #2

can someone show me a better way of accessing these elements besides the subscript operator. I cant work it out because of the nesting of vectors.
the vector should be a 0-31 by 0-31 int vector initialized to 0; i think its correct. i am just trying to decide if there is a better way to access the stuff. the subscript operator seems the most natural because i can picture the grid in my mind but everyone says its unsafe. i will need to access array elements both to the right of individual elements. also to the left and to the top and bottom.

this is what i have so far. note that this code is not 100% mine. it has been modified for my usage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>

using std::cout;    using std::endl;
using std::vector;  using std::cin;

int main(int arg, char** argv)
{

	vector< vector < int > > vMatrix(32,vector< int >(32,0));

	vMatrix[1][2] = 1;
	vMatrix[3][1] = 6;
	vMatrix[31][31] = 9;

	cout << vMatrix[1][2] << endl;
	cout << vMatrix[3][1] << endl;
	cout << vMatrix[31][31] << endl;
	cout << vMatrix[19][16] << endl;

    cin.get();
}

Last edited on
It's unsafe, true, but it works. If you still want to be sure, though, you may use the .at() member function in place of your [] operators.

http://cplusplus.com/reference/stl/vector/at/

Happy coding!

-Albatross
Last edited on
operator[] may allow you to access locations outside the vector. If you want to be sure that you never do that you can use the vector::at method. It's the same as operator[] but if the index is out of range, it throws an exception

http://www.cplusplus.com/reference/stl/vector/at/
ok thanks and happy coding
i think im going to end up using the subscript operator. i looked at the example code for myvector.at(num) = myint but i cant figure out the syntext for a two dimensional vector of vector. i tried numerous combos and they always spit out an error.
vector::at returns a reference to the object contained ( exactly as operator[] )
Topic archived. No new replies allowed.