Why doesn't my cout work?

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
#include <iostream>
#include <vector>
using namespace std;


int main()
{
	vector<vector<int>> row{ { 5}, { 2 }, { 5 } };
	for (auto v : row) {
		for (auto x : v) {
			cout << x << " ";
		}

		cout << endl;
	}

	row[2].pop_back();

    cout << endl << row[2][0] << endl << endl;//why does this still show the old value?

	cout << endl;
	for (auto v : row) {
		for (auto x : v) {
			cout << x << " ";
		}

		cout << endl;
	}
}



I've commented the part of the code that doesn't work as I expect it to and don't understand why?
Last edited on
That is undefined behavior. You're accessing an element that no longer exists. You got unlucky and it happened that you got the value that used to be there. If you were lucky your program would crash and prevent further corruption. However since the behavior is undefined, the compiler is fully allowed to replace that code with code that shuts down your computer. Anything can happen.

If you want defined behavior, use .at() instead - it will throw an exception instead of corrupting your program.
Thanks for letting me know what happens behind the scenes.

So I've written this which helps me better than the c++ 11 code up there. I don't understand it much but I do understand what I myself wrote here.

1
2
3
4
5
6
7
    for(int i =0 ; i <= row.size()-1; i++)
    {
        for(int j = row.at(i).size()-1; j >= 0;j--){
        cout << row[i][j];
        }
        cout << endl;
    }


Edit: don't tell me how to solve my problem here. I'm busting my head thinking of the algorithm but it's a really fun challenge for me. Sorry if anyone is working on it. I removed what I'm trying to accomplish that I couldn't figure out.
Last edited on
i <= row.size()-1; DO not write like that. It is a bug. If row size is 0, then if you deduct one, you will get 18,446,744,073,709,551,615 on 64bit system, or 4,294,967,296 on 32bit one. Useage of <= in loops is alway suspicious if loop variable is used as index.

Canonical way to write your loop is: for(int i = 0; i < row.size(); ++i)
Topic archived. No new replies allowed.