Shadow97
Shadow97

Reputation: 151

C++: std::vector<std::vector<T>> comes back as a vector of empty vectors when passed into a fill function by reference

Stripped down to a minimal reproducible example, the code I'm having the issue with is as follows:

#include <iostream>
#include <vector>

using namespace std;

void fill_vector_of_vectors(vector<vector<char>>& data) // I gave up on trying to think up a proper name for this
{
    data.clear();
    data.resize(4);
    for (vector<char> subarray : data)
    {
        subarray.resize(4, 'x');
    }
}

int main()
{
    vector<vector<char>> data;
    fill_vector_of_vectors(data);
    for (vector<char> subarray : data)
    {
        for (char must_be_x: subarray)
        {
            cout << must_be_x;
        }
        cout << "\n";
    }

    return 0;
}

Expected output is

xxxx
xxxx
xxxx
xxxx

But the actual output of the code is four blank lines. With the debugger, I found out that the filler function does fill out the child vectors properly, but the child vectors in main() are empty. Where am I losing the data?

Upvotes: 3

Views: 84

Answers (1)

Shadow97
Shadow97

Reputation: 151

The reason the changes to the child vectors made in the filler function did not reflect in the context outside of it was the misuse of the iterating for statement. In this line,

for (vector<char> subarray : data)

subarray is actually the copy of the child vector of the vector the reference whichof has been passed to the function, so the changes I made to it naturally didn't reflect in the actual child vector. Changing this line to

for (vector<char>& subarray : data)

Fixed the issue.

Upvotes: 6

Related Questions