Problems to understand vector allocation

Hello,

I am trying to understand the vector in 2D and how to print it in horizontal and vertical way but it seems I am doing something wrong and/or I am not understanding. I hope some of you could please give me the proper insight.

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
  int nx = 3;
  int ny = 3;
  int msize = nx*ny;

  std::vector< std::vector<int> > f;
  std::vector<int> row;

	for (int j = 0; j < ny; j++) {
		row.push_back(j);            // put values 0 1 2 in row
	}
	f.push_back(row);                    // place vector 0 1 2 in vector f
	

	for (int j = 0; j < ny; j++) {
		row.push_back(j+msize);      // put values 9 10 11 in row
	}
	f.push_back(row);                    // place vector 9 10 11 in vector f
	

// Print two rows as two different vectors
	std::cout << "Your matrix f is:" << std::endl;
	for (int row = 0; row < 2; row++){
		for(int col = 0; col < 3; col++) {
			std::cout << f[row][col] << "  ";
		}
		std::cout << std::endl;
	}


This code prints two rows as:
0 1 2
0 1 2

Why I cannot move to the second vector I pushed back in the second for??

Thank you in advance :)
Why I cannot move to the second vector I pushed back in the second for??

You are moving to the second vector.

At lines 8 - 10, you push 3 numbers onto row. After this, the elements of row are:

0 1 2

You then copy row into f as the first element of the vector.

At lines 14 - 16, you push another 3 numbers onto row. After this, the elements of row are:

0 1 2 9 10 11

You then copy row into f as the second element of the vector. The full contents of f are now:

0 1 2
0 1 2 9 10 11

When you print out the contents of f, you're only printing the first 3 elements of each vector, so you get:

0 1 2
0 1 2

If you change your printing loop to:

1
2
3
4
5
6
7
8
	for (int row = 0; row < f.size(); row++)
        {
		for(int col = 0; col < f[row].size(); col++) 
                {
			std::cout << f[row][col] << "  ";
		}
		std::cout << std::endl;
	}


you'll see the full contents of each element of f.
Last edited on
Thanks MikeyBoy, I see what I'm doing now.

I managed now to have the vector 0 1 2 and 9 10 11 in f; now I want to print them in a transpose way, i.e.:

0 9
1 10
2 11

I know it may seem strange but the thing is that first I obtain vector 0 1 2 and later I calculate the other values, but I need to present them in such manner.

I tried something like:

1
2
3
   for (int i = 0; i < f.size(); i+2) {
		std::cout << f[i] << '  ';
		}
)

But of course that increment did not work. Is there any other way to declare increments other than i++??
Ok I did it twice and worked out i++, i++
But I'm sure there should be a more efficient way...
i++ is just another way of saying i += 1 or i = i + 1.

So, if instead of incrementing by 1, you want to increment by 2, it shouldn't be too hard to figure out what to write...
Topic archived. No new replies allowed.