counts[k] = make_pair<string, int>(s, count_inversion(pos, 0, pos.size()));
Whenever make_pair
is used like make_pair<string,int>(s,i)
it gives an error:
error: no matching function to call for 'make_pair(std::__cxx11::string&, int)'
note: cannot convert 's' (type 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}') to type 'std::__cxx11::basic_string<char>&&'
However make_pair<string&,int>(s,i)
works fine. Can somebody explain this. If the variable s
is changed after make_pair
call in the latter case, will it affect the pair?
std::make_pair
is intended to be used without explicitly specifying template arguments. And since C++11, it uses perfect forwarding, which makes it very hard (and even more pointless) to supply template arguments manually.
Use std::make_pair
when you want to deduce the types in the pair from the types of the arguments to make_pair
.
Use std::pair<T, U>
when you want explicit control of the types in the pair.
Notice that in your case, calling make_pair(s, count_inversion(pos, 0, pos.size()))
will actually deduce the templte parameters to string&
and whatever the return type of count_inversion is
. This doesn't mean the pair will contain a reference, it's just perfect forwarding in action. So the produced pair will contain a copy of s
and will not be affected by future changes to s
.
Using std::pair<string&, int>
would be different and would indeed give you a live reference to s
in the pair.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With