- #1
Absolutism
- 28
- 0
Homework Statement
I came across some codes that calculate the smaller string using user-defined functions.
I tried figuring them out, but some parts I don't get. This is the first one:
bool isShorter (string& s1, string& s2) { // the string objects may be large!
return s1.size( ) < s2.size( ); // checks whether the first string object is shorter
} // then the second: no need to copy the strings
int main ( ) {
string A(“Hello, “); string B(“John!”);
if ( isShorter (A,B) )
cout << “The shorter string is: “ << A << endl;
else if ( isShorter (B,A) )
cout << “The shorter string is: “ << B << endl;
else cout << “The two strings are of equal length” << endl;
}
That part in bold, I don't get. Isn't that a bool? and it should return true/false? Besides, should we not account for the condition of s2 being smaller than s1 too?
The other question is basically about a similar code, put in a different way.
That is the function:
bool isShorter (const string& s1, const string& s2) {
return s1.size( ) < s2.size( ); // checks whether the first string object is shorter
} // then the second: no need to copy the strings
I don't get the use of "const" here. Can someone explain?
This is the main:
int main ( ) {
string A(“Hello, “); string B(“John!”);
if ( isShorter (A,B) )
cout << “String “ << A << “ is shorter than “ << B << endl;
if ( isShorter (“Hello, “, “John!”) )
cout << “The shorter string is: “ << “Hello, “ << endl;
}
Homework Equations
The Attempt at a Solution
I have tried to write a similar program using strings, which should be pretty simple:
#include "iostream"
#include "string"
using namespace std;
string isShorter (string s1, string s2)
{
if (s1.size() <s2.size())
return s1;
else
return s2;
}
int main ()
{
string x;
string y;
string z;
getline (cin, x);
getline (cin, y);
z=isShorter (x,y);
cout<<z;
return 0;
}
But I was told that this way, it is not efficient for larger strings.