Search code examples
c++vectorstructure

Vector push back function in structure not working


I want to store a vector in a structure and then append to the vector from a function. Does this even make sense or can I only create elements in my vector when creating it? If no, where is the error in the code below, because if I execute it, it simply prints nothing. I want it to store the numbers 0-4 as components of the vector nums in holder.

#include "iostream"
#include "vector"

using namespace std;

struct layers{
    vector<float> nums;
};

void range(layers layer){
    for(int n = 0; n< 5; n++){
        layer.nums.push_back(n);
    }
}

int main(){
    layers holder;
    range(holder);
    for(int k  = 0; k < holder.nums.size(); k++){
        std::cout << holder.nums[k] << " ";
    }
    return 0;
}

Solution

  • You have to pass the layer parameter by reference, not by value. Instead of void range(layers layer), do void range(layers &layer).

    If you pass by value, you are making a copy of the vector and then modify this copy inside the function, so your original vector remains untouched. If you pass by reference, the original vector is modified.

    Try it online!

    #include "iostream"
    #include "vector"
    
    using namespace std;
    
    struct layers{
        vector<float> nums;
    };
    
    void range(layers & layer){
        for(int n = 0; n< 5; n++){
            layer.nums.push_back(n);
        }
    }
    
    int main(){
        layers holder;
        range(holder);
        for(int k  = 0; k < holder.nums.size(); k++){
            std::cout << holder.nums[k] << " ";
        }
        return 0;
    }
    

    Output:

    0 1 2 3 4