2
template<typename s>
void vecprint2d(const s& vec){
    cout<<"{"<<endl;
    for(int x = 0; x < vec.size(); x++){
        cout<<"{";
        for(int y = 0; y < vec[x].size() - 1;y++){
            cout << vec[x][y]<<", ";
        }
        cout<<vec[x][vec[x].size() - 1]<<"}"<<endl;
    }
    cout<<"}"<<endl;
}


int main(){
vector<vector<int>> vec = {{1,2,3},{},{4,5,6}};
vecprint2d(vec);
return 0;
}

in my attempt at a function for printing a vector of vectors, why does cout inside the inner loop cause problems, or is the problem elsewhere?

the output right now looks like:

{

{

2wings
  • 71
  • 1
  • 7

2 Answers2

3

If the inner vector's size is 0, size() - 1 will overflow and it will loop forever and/or crash. Could that be what is happening on your raspberry pi?

To avoid this, handle 0-sized vectors as well.

For example like this:

template<typename s>
void vecprint2d(const s& vec) {
    cout << "{" << endl;
    for (auto const& row : vec) {
        cout << "{";
        int i = 0;
        for (auto const& val : row) {
            if (i++)
                cout << ", ";
            cout << val;
        }
        cout << "}" << endl;
    }
    cout << "}" << endl;
}
rustyx
  • 80,671
  • 25
  • 200
  • 267
0

The size() function of an empty vector will return an (unsigned) value of zero and, in your inner loop, you test y against vec[x].size() - 1. This will give a value that has 'underflowed' and thus have the maximum value that a size_t variable can hold, so the y loop will run a very large number of times! However, it will likely fail on the first loop, because trying to access any element of an empty vector is undefined behaviour.

To fix this, enclose your inner loop in an "is it empty" if block (in fact, you should do this for both loops). Here's a possible solution:

template<typename s>
void vecprint2d(const s& vec)
{
    cout << "{" << endl;;
    if (!vec.empty()) for (size_t x = 0; x < vec.size(); x++) {
        cout << "{";
        if (!vec[x].empty()) {
            for (size_t y = 0; y < vec[x].size() - 1; y++) {
                cout << vec[x][y] << ", ";
            }
            cout << vec[x][vec[x].size() - 1];
        }
        cout << "}" << endl;
    }
    cout << "}" << endl;
}

Feel free to ask for further clarification and/or explanation.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83