Search code examples
c++vectorpush-back

Why can't I directly push_back update value from function in vector?


push_backing to a vector with function updated values doesn't permit why?

std::vector< std::string >goin;
goin.push_back(function(somestringvalue)); // why cant it take update value?

void function(std::string& var)
{
    var += "pre";
}

Solution

  • As others have said, the problem is that function doesn't return anything. The way to fix this is to have it return its argument:

    const std::string& function(std::string& var) {
        var += "pre";
        return var;
    }
    

    This way it modifies the string that's passed to it, and it returns a reference to that string so that you can push it into the vector.