print vector function with an iterator going too far

So this here function works perfectly except it is going one past and prints jibberish into my final element, and I can't figure out the flaw in my logic. Any ideas?
*note: this is homework, so I have to print it with an array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void print(vector<int>v1) {
    int height = v1.size()/10;
    vector<int>::iterator it = v1.begin();
    if (v1.size()%10!=0) {height++;}
    int p[height][10];
    for (int z=0;z<height;z++){
        for (int x=0;x<10;x++){
            p[z][x] = *it;
            if (it == v1.end()) {break;}
            it++;
        }
    }
    for (int z=0;z<height;z++){
        for (int x=0;x<10;x++){
            if ((z*x) == v1.size()){break;}
            cout << setw(3) << p[z][x];
        }   cout << endl;
    }
}
Last edited on
vector<T>::end() does not represent the last element in a vector, it represents one past the last element; p[z][x] = *it; needs to move down a line. Also, the 'break' statement doesn't break out of both for loops - only the inner one (x=0...etc)

In the 2nd for loop, to see when you've reached the end, you should be looking at z*10 + x, not z*x (think about it).
Last edited on
Just to be sure, is this what you meant? Seems to work perfect! Thanks so much!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void print(vector<int>v1) {
    int height = v1.size()/10;
    vector<int>::iterator it = v1.begin();
    if (v1.size()%10!=0) {height++;}
    int p[height][10];
    for (int z=0;z<height;z++){
        for (int x=0;x<10;x++){
            if (it == v1.end()) {break;}
            p[z][x] = *it;
            it++;
        }
            if (it == v1.end()-1) {break;}
    }
    for (int z=0;z<height;z++){
        for (int x=0;x<10;x++){
            if ((z*10)+x == v1.size()){break;}
            cout << setw(3) << p[z][x];
        }   cout << endl;
    }
}
Yep, that's correct - take a minute to make sure you understand why it works though!
Oh, naturally! I totally get it now, just didn't see it before
Topic archived. No new replies allowed.