0

I having a problem using push_back(), I can't figure out why only the first cols vector is just pushed over and over again.

Input

10 9 10 3 100 8 7 10 73 9 10 5 9 87 -1 8 3 7 10 92 6 10 6 83 9 11 8 8 77 -1 10 10 10 10 100 10 10 10 100 10 10 10 10 100 -1 DONE


C++

(...)

size = numbers.size();
counter = 0;
square = ceil(sqrt(size));
vector < vector <int> > rows;
vector<int> cols;

do {
    for (int i = 0; i < square; ++i) {
        cols.push_back(numbers[counter]);
        cout << cols[i] << " ";
        ++counter;
    }
    rows.push_back(cols);
    cout << endl;
} while (counter <= size);
(...)



Undesirable Output

0:   10   9  10   3 100   8   7
1:   10   9  10   3 100   8   7
2:   10   9  10   3 100   8   7
3:   10   9  10   3 100   8   7
4:   10   9  10   3 100   8   7
5:   10   9  10   3 100   8   7
6:   10   9  10   3 100   8   7

rows[1][2] should be 73, not 9. Where have I gone wrong?

nipponese
  • 2,813
  • 6
  • 35
  • 51

2 Answers2

1

You never reset cols. Instead you just keep adding on to it. I think you are printing rows out with magic number indices, which is why you do not spot the added portion. Either declare a temporary cols inside the loop or call clear after each push_back().

yizzlez
  • 8,757
  • 4
  • 29
  • 44
  • Ah, good advice. I used `cols.clear()` and it worked, but why doesn't the contents of the vector just get over-written like any other variable? – nipponese May 18 '14 at 02:43
  • 1
    Your `pushing_back()` which means that it adds on to the `vector` and increases its size. – yizzlez May 18 '14 at 02:44
  • So the new additions to the vector never get copied into the parent vector because they exceed `square` (`7`, in this case)? – nipponese May 18 '14 at 02:56
  • 1
    They do. You are probably just not printing them out. – yizzlez May 18 '14 at 03:00
0

awesomeyi found your main problem. But your code has other issues too.

There is a buffer overflow. For example if size == 4 then square == 2 and we get:

  • after iter #1: counter == 2; continue since 2 <= 4
  • after iter #2: counter == 4; continue since 4 <= 4
  • iter #3: reads numbers[4] and numbers[5] - oops!

The loop condition should be:

while (counter + square <= size);

we need to make sure that the next iteration will complete without overflowing the vector. It would be smart to use .at() for vector access so that if you did make a miscalculation, then the error will behave nicely instead of going screwball.

The loop (minus the output) could actually be written as:

for (size_t counter = 0; counter + square <= size; counter += square )
{
    std::vector<int> cols( numbers.begin() + counter, numbers.begin() + counter + square );
    rows.push_back(cols);
}
M.M
  • 138,810
  • 21
  • 208
  • 365