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;
}
}
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).