iterating over a 2d vector

Ok so i managed to learn vectors..one d...then now how to create 2d..fantastic..i can easily move up and down the 1D vector...but nowhere on this site am I finding how to iterate over a 2d vector like i do iterate over my array matrix...
can someone give me a good tutorial? thanks...i wish to be able to do all the iteration i do on an array matrix on a 2D vector too...any link or site with a good tutorial and nice examples will be very much appreciated..thanks..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iomanip>
#include <iostream>
#include <vector>

typedef std::vector<std::vector<int>> vector2d;

vector2d CreateVector2d()
{
    vector2d v2d(3, std::vector<int>(3));

    for (unsigned i = 0; i < 3; ++i)
        v2d[i][i] = 1;

    return v2d;
}

void print(std::ostream& os, const vector2d& v)
{
    // C++11:
    for (auto & vec : v)
    {
        for (auto & i : vec)
            os << std::setw(2) << i;
        os << '\n';
    }

    // or:
    //for (vector2d::const_iterator i = v.begin(); i != v.end(); ++i)
    //{
    //    for (std::vector<int>::const_iterator j = i->begin(); j != i->end(); ++j)
    //        os << std::setw(2) << *j;
    //    os << '\n';
    //}

    // or:
    //for (unsigned i = 0; i < v.size(); ++i)
    //{
    //    for (unsigned j = 0; j < v[i].size(); ++j)
    //        os << std::setw(2) << v[i][j];
    //    os << '\n';
    //}
}

int main()
{
    print(std::cout, CreateVector2d());
}


http://ideone.com/4xnFYA
haha am not understanding anything...some more comments...is the very first time..take it like i just heard about vectors yesterday...can you give comments and do step by step explanation like you're explaining to a five year old? thank you? iomanip? well am gonna read about that..typedef ecc? why std infront of everything...can't i do without it?
If you know how to navigate your array matrix (which I think is a 2D array), you shouldn't have issues of navigating 2D vectors.

Maybe post how you navigated your 2D array so it can be adapted to show how 2D vectors are done? Besides you can use subscripts [] on vectors as well.
If you understand a 1 dimensional vector, then it shouldn't be that much of a reach. A 2 dimensional vector is simply a vector which contains more vectors. You iterate over the outer vector (the outer for loops above) to get to the inner vectors which you then iterate over to get your data (the inner for loops above.)

Lines 36 to 41 above should look rather like how you would access a 2d array. I suspect that is what you were after.

std::setw sets the minimum field width for the next output operation.

why std infront of everything...can't i do without it?

You could with an appropriate using directive (or directives.) As for the 'why', because it is a good practice.
Topic archived. No new replies allowed.