vector<vector<T> > is kinda like 2D, right? How would I insert something to it? I know how to do it with vector<T> but my brains seem to sprain when figuring this one out (perhaps 'cause this was the very first day when I did something with STL).
vector<vector<T> > is kinda like 2D, right? How would I insert something to it? I know how to do it with vector<T> but my brains seem to sprain when figuring this one out (perhaps 'cause this was the very first day when I did something with STL).
kooma - [email protected]
You could do something like -
Code:#include <iostream> #include <vector> using namespace std; int main ( void ) { vector<vector<int> > i; vector <int> temp1; temp1.push_back(1); temp1.push_back(2); vector <int> temp2; temp2.push_back(3); temp2.push_back(4); i.push_back(temp1); i.push_back(temp2); cout << i[0][0] << i[0][1] << i[1][0] << i[1][1]; return 0; }
This is probably clearer, as long as you note that the inner vectors are limited to a size of 20 -
Although you could resize the inner vectors doing -Code:#include <iostream> #include <vector> using namespace std; int main ( void ) { vector<vector<int> > i; vector <int> temp1(20); i.push_back(temp1); i.push_back(temp1); i[0][0] = 1; i[0][1] = 2; i[1][0] = 3; i[1][1] = 4; cout << i[0][0] << i[0][1] << i[1][0] << i[1][1]; return 0; }
i[0].resize(30);
or dynamically push elements on the back using
i[0].push_back(21);
which would then be accessed like -
cout << i[0][20];
Just what I figured out an hour later after posting... :-) But, what I was after was how to do it without that temp variable; is it possible to hardcode that temp1 in?
kooma - [email protected]
Note that moving a vector is expensive so compound containers will be quite inefficent (the STL thinks of a move as a copy followed by the destruction of the source, see Typed Buffers at www.moderncppdesign.com for a workaround).Code:#include <vector> using std::vector; int main() { int width = 10; int height = 10; // Create a vector of width vectors of height ints vector<vector<int> > vecvec(width, vector<int>(height)); }
- lmov
Ummm, I have never seen that syntax before: vector<vector<int>> i
What does it do? Whats the differens from int i[?][?]?
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.