Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL Push_back string in vector

Tags:

c++

stl

vector

I am trying to push a string in a string vector, like below

void Node::set_val(string &val)
{
    this->val.push_back(val);
}

But when I try to call it as below

Obj.set_val("10h;");

I get the below error,

error: no matching function for call to 'Node::set_val(const char [5])'

I assumed that the string in " " is same as string in c++, Why do I get such an error? What has to be changed below?

like image 480
Bharadwaj Avatar asked Jan 23 '26 22:01

Bharadwaj


1 Answers

You are taking in a std::string by non-const reference. Non-const references cannot bind to rvalues, like "10h;", so you can't pass literals in to that function.

If you aren't going to modify the argument, you should take your argument by reference-to-const:

void Node::set_val(const string &val)
//                 ^^^^^

This way, a temporary std::string will be constructed from your const char[5] and passed in to set_val.

You could improve this by taking in the string by value and moveing it into the vector:

void Node::set_val(string val)
{
    this->val.push_back(std::move(val));
}

This prevents you from making some unnecessary copies.

like image 104
TartanLlama Avatar answered Jan 26 '26 13:01

TartanLlama