C++ User-defined function to calculate the smaller string?

In summary, the conversation is about user-defined functions that calculate the smaller string. The first function, isShorter(), compares the sizes of two string objects and returns a bool value indicating whether the first string is shorter than the second. The use of "const" in the second function, isShorter(), means that the string objects being compared cannot be modified within the function. This is to prevent any accidental changes to the strings. The main function uses these functions to compare strings and output the shorter one. Lastly, the attempt at a solution includes a similar program using strings, which may not be efficient for larger strings.
  • #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.
 
Physics news on Phys.org
  • #2
Absolutism said:

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 stringsI 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.

I want to make a general statement first. It is often good to give pieces of code names to clarify meaning. In these pieces of code, they try to do that with isShorter(). But in my opinion, that function actually obscures meaning through over-complication. I had to look back constantly at the function definition to see if isShorter(a,b) checked whether a was shorter than b or if it checked whether b was shorted than a. It would have been simpler (and more understandable to me) if the code simply put the one-liner length comparison in main.

As for your first question, that is indeed a bool aka true or false. But it isn't the entire program. It is merely a piece of reusable code that is jumped to from main. In other words, in the code encased by "int main{}", wherever you see isShorter(string1, string2), the code communicates the contents of string1 and string2 to the code in isShorter, runs the code in isShorter, and then returns that Boolean result. So an equivalent program would be:

Code:
int main ( ) 
{
string A(“Hello, “); string B(“John!”);
if ( A.length < B.length )
    cout << “The shorter string is: “ << A << endl;
else if ( B.length < A.length )
    cout << “The shorter string is: “ << B << endl;
else 
    cout << “The two strings are of equal length” << endl;
}

As for your second question, you can send data (e.g. a string) to a function by reference or value.

If I sent it by value, the function has "randomFunction(string willBeValueOfString)" and main can send the contents of aString with "randomFunction(aString)". In this circumstance, it takes the computer some time to replicate each entry in aString to give to randomFunction. This makes it slower for larger data sets. But there is a benefit to the decrease in speed: randomFunction can demolish the data it receives etc. without main's aString changing at all! Main, after all, made a copy and gave it to randomFunction for this security.

If sent by reference ("randomFunction(string& willBeRefOfString)"), main actually sends directions to the same data that main is using. If main does randomFunction(aString), when main gets back in control, aString can actually have different values from when it called randomFunction. For example, it could send "frog" to randomFunction only to have "abcd" be in aString afterward. Despite this potentially bad possibility, it has a benefit: There is no replication of data, so it is faster than sending by value for large data sets. (Note, the potential changing of data with a pass by reference can be used beneficially if, for example, you use an input argument actually as an output -- as in, main says, "Here is aString. Please put into it what I expect you to put in there.")

Summary: Sending by value has data security for main but can be slower. Sending by reference has no data security yet can be faster. I have not tested it, but if you send a single integer, it makes sense that a pass by value or reference will take the same amount of time, explaining my careful wording of "can be" faster or slower.

So what if you want the potential added speed of sending by reference without the potential destruction of your data? You know 100% that the function has no reason to change your data, but unless the c++ environment makes it 100% certain it will not happen, you don't feel safe giving it your precious data. What you do here is in your function, pass a constant reference. So you send directions to the data still, hence being possibly faster than a pass by value, but the function cannot change the values of aString. If it ever tries to change it in the source code, you will get a compiler error. It will never be a run-time issue.

In sum, a pass by constant reference is proper if you send the contents of some variable by reference without the intention of changing the values of that variable relative to the caller by the callee (e.g. keep aString in main the same after calling randomFunction). Further, it is customary to pass argument by reference if you are dealing with something that has more than one value in it such as a string.
 
Last edited:

What is a user-defined function in C++?

A user-defined function in C++ is a function that is created by the programmer to perform a specific task. It allows for more organized and modular code by breaking down complex tasks into smaller, reusable functions.

How do I declare a user-defined function in C++?

To declare a user-defined function in C++, you need to specify the return type, function name, and any parameters it takes. For example:
int smallerString(string str1, string str2);
This declares a function named "smallerString" that takes two string parameters and returns an integer value.

How do I define a user-defined function in C++?

To define a user-defined function in C++, you need to specify the return type, function name, and any parameters it takes, followed by the function body enclosed in curly braces. For example:
int smallerString(string str1, string str2) {
// function body
}
This defines a function named "smallerString" that takes two string parameters and returns an integer value.

How do I call a user-defined function in C++?

To call a user-defined function in C++, you simply need to use its name followed by parentheses and any necessary arguments. For example:
int result = smallerString("hello", "world");
This calls the "smallerString" function with the strings "hello" and "world" as arguments, and assigns the returned value to the variable "result".

What are the benefits of using user-defined functions in C++?

There are several benefits of using user-defined functions in C++, including improved code organization, easier debugging and maintenance, and the ability to reuse code for similar tasks. User-defined functions also make it easier to collaborate with other programmers and can improve the overall efficiency of your code.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
935
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
750
  • Engineering and Comp Sci Homework Help
Replies
3
Views
938
  • Engineering and Comp Sci Homework Help
Replies
24
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
14
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
2K
Back
Top