Create a copy or use reference for parameter?
My problem is that I want to return a common substring of two strings s1, s2. Apparently, s1 and s2 are symmetric.
string shortest_common( const string& s1, const string& s2 ) {
}
There are three possible solutions to this problem that I came up with:
- Either make a copy of s1 and s2
- Or swap them, which means I have to sacrifi开发者_如何学编程ce their const-ness
- Or worst, duplicate code!
I personally prefer the first case, since intent is to find the shortest-common string not changing s1 or s2. So my question is: Which option is ideal in this case?
Thanks,
ChanI would opt to go with the signature that you've displayed. If you're finding a common substring then you don't want to have side-effects. That's not what people think of when they would call your function. I don't expect a function called "add_two_numbers" to modify one of the numbers and return a value.
You could use recursion to swap the meanings of parameters without changing the objects themselves in any way.
I'm a bit confused as to what your actual question is, so I'll judge by the title.
Do both:
void shortest_common( string& s1, const string& s2 )
{
// real algorithm changing s1
}
inline string shortest_common( string s1, const string& s2 )
{
shortest_common( s1, s2 );
return s1;
}
精彩评论