Trending February 2024 # How Does Collect Function Work In Scala With Examples # Suggested March 2024 # Top 10 Popular

You are reading the article How Does Collect Function Work In Scala With Examples updated in February 2024 on the website Cattuongwedding.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How Does Collect Function Work In Scala With Examples

Introduction to Scala collect.

Collect function is used to collect elements from the given collection. Collect function can be used with the collection data structure to pick up some elements which satisfy the given condition. Collect function can be used with the mutable and immutable collection data structure in scala. It always returns us the new collection containing all the elements that satisfy the condition; this condition is referred to as the Partial function. That means it took the partial function and applied it to the all the values present inside the given collection.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

We know that it is a function available in Scala, which takes up the partial function as the parameter and will be applied on all the variables present inside it and return us the elements that satisfy the condition.

Let’s see the syntax of this function.

This is the syntax as per the scala doc:

def collect[B](pf: PartialFunction[A, B]): Traversable[B] mylistName.collect(Your_partial_function)

As you can see in the above lines of code, we can call this function on our collection object by specifying a partial function inside it as the parameter. So after calculating the values, it will return us a new collection with result values inside it.

How does collect Function Work in Scala?

We know that the collect function in scala to collect the element from a collection that are of the same type. We can call this function on any collection type, whether it is mutable or immutable. It will always return us the new collection as a result of the given collection element.

Method signature:

def collect[B](pf: PartialFunction[A, B]): Traversable[B] (This is as per the scala documentation)

1. Partial Function

The collect function takes a partial function as the parameter. This partial function will be responsible for performing the operation on the each element of the collection. It will pick out all the elements from the given collection that will satisfies the partial function.

Syntax:

In the above lines of code, we can define a partial function, what it will take and what it is going to return. This is simple to use and readable also.

val demo: PartialFunction[String, String] = { }

In the above lines of code, we are creating one partial function which will take up the string parameter and return us the string. In this way, we can specify our type what we want from the given collection.

2. Return Type

Collect function will always return us the new collection, which will contain all the elements from the given collection data structure.

Example:

object Main extends App{ val mysequence: Seq[Any] = Seq("hello", "hello again", 40, "bye", 60, 80, 100, "i am strinf as well !!") }

It is just a simple program in which we are creating a sequence of ‘any’ type in scala; also, we are specifying the different type of element inside it, for instance, string and integer. But we want to extract only the string elements from the collection, so we call the collect method and pass our partial function to match only the string. In this way, we can use a collect function in scala.

Points to be remembered while using a collect function in scala:

This can be used with the mutable and immutable collection data structure.

This function takes a partial function as the argument; this function will calculate and pick up the elements which satisfies the given condition. Always it will return as a result in the form of a new collection contain all the element.

Examples of Scala collect.

Given below are the examples of Scala collect:

Example #1

In this example, we are creating a sequence collection of any type. Using the collect function, we are trying to extract the integer, string, and double values from the given collection data structure in the scala.

object Main extends App{ println("Demo to understand collect function in scala !!") println("Extrat only string values ::") val mysequence1: Seq[Any] = Seq("hello", "hello again", 40, "bye", 60, 80, 100, "i am string as well !!") println("Result is ::") println(result1) println("***********************************************************************") println("Extrat only integer values ::") val mysequence2: Seq[Any] = Seq("Amit", 200, 20.1, "sumit", 300, 30.2, "Geet", 400 , 40.1, "vinit", 500, 50.1) println("Result is ::") println(result2) println("***********************************************************************") println("Extrat only double values ::") val mysequence3: Seq[Any] = Seq("Amit", 200, 20.1, "sumit", 300, 30.2, "Geet", 400 , 40.1, "vinit", 500, 50.1) println("Result is ::") println(result3) }

Output:

Example #2

In this example, we are trying to fetch the float value from the collect data structure. Here also we are using the collect function to extract the element from the collection. Also, we are not using any library; this is an in build function available in scala.

Code:

object Main extends App{ println("Demo to understand collect function in scala !!") println("Extrat only float values ::") val mysequence1: Seq[Any] = Seq(2.1f, "test 1", "test2", 5.7f, "test 3", "test 4", "tets 5", 8890, 1.0f, 8.9f, 2.4f) println("Result is ::") println(result1) println("***********************************************************************") }

Output:

Conclusion

By using the collect function, we can easily extract the data from the collection, which are of the same type. Also, we can use this function with any mutable and immutable collection data structure, which makes it more easy and more handy to use.

Recommended Articles

We hope that this EDUCBA information on “Scala collect” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How Does Collect Function Work In Scala With Examples

How Does Reinvestment Risk Work With Examples?

What is Reinvestment Risk?

The term “reinvestment risk” refers to the risk wherein an investor might be unable to reinvest the cash flows from current investments(such as coupons received from bond investments) at a rate equal to the current return.

Although it is primarily associated with bond investments, any investment that generates cash flow remains exposed to reinvestment risk.

Start Your Free Investment Banking Course

Download Corporate Valuation, Investment Banking, Accounting, CFA Calculator & others

Explanation of Reinvestment Risk

When the overall market interest rates decrease, the value of fixed-rate bonds with higher coupons surges, enticing some bondholders to sell the bonds for a profit. But, on the other hand, the other investors hold onto their bond investments as they might not be able to earn as much interest income by reinvesting the proceeds from the investment sale, which is precisely due to reinvestment risks –lower market interest rates resulting in a lower yield to maturity.

How Does Reinvestment Risk Work?

It primarily functions in the following two ways:

Reinvestment Risk in Callable Bonds: The holders of callable bonds are constantly exposed to the risk of premature buyback of the bonds by the issuers, which becomes more pronounced in a falling interest rate environment. In this case, the reinvestment risks arise when the interest rates fall and the issuers refinance their bond obligations leaving the investors with no other options but to reinvest the proceeds at a lower rate.

Reinvestment Risk in Coupon Paying Bonds: The holders of coupon bonds receive regular coupon payments, which becomes the source of reinvestment risk in this case. In case of falling interest rates, the investors cannot reinvest the coupons at a rate equal to the bond investments.

Reinvestment Risk in Zero-Coupon Bonds: Even though zero-coupon bonds remain free from reinvestment risks until the maturity of the bonds, they become exposed to this risk when the bond investments mature, and the proceeds need to be reinvested.

Example of Reinvestment Risk

Different examples are mentioned below:

Example #1

Let us take the example of David, who purchased ten 10-year $1,000 bonds offering 5%as an annual coupon. However, the market interest rates are expected to decline during the next ten years to 3%. Explain the reinvestment risk in this case.

Example #2

Take the example of 5-year callable bonds issued by XYZ Inc. and purchased by John. The bonds offered an annual coupon rate of 6%. However, the market interest rates declined to 4% two years after the bond issuance. Consequently, XYZ Inc. decided to grab the opportunity to refinance its debt at a lower rate (by exercising the call-back right). Discuss John’s reinvestment risk in this case.

Here, John will have to reinvest the proceeds from the called-back bonds at 4% instead of the 6% coupon rate earned on the bond investment. This is the reinvestment risk for John in this case.

How to Avoid Reinvestment Risk?

The following ways can be used to mitigate it:

Investment in non-callable bonds or securities helps avoid reinvestment risk as this technique prevents issuers from calling back high coupon-paying bonds when market interest rates go down.

Investment in zero-coupon bonds also helps investors avoid reinvestment risks to a large extent, as these bonds don’t result in any intermediate cash outflow in the form of coupons.

Investors can construct a bond ladder, a bond portfolio with varying maturity dates. Bonds maturing in a high-interest rate environment offset losses (notional) incurred due to maturity in a low-interest rate market, thereby addressing and mitigating the reinvestment risks. This has implications for the overall investment strategy.

Advantages

The value of the fixed coupon payment received from the bonds increases for investors.

It is beneficial for borrowers to either raise more debt or refinance existing debt at favorable rates.

It results in a lower realized yield than the expected return rate.

It is almost impossible to eliminate the reinvestment risks for any investment.

Investors who prefer short-term bond investments primarily face exposure to reinvestment risk.

Conclusion

So, it can conclude that although reinvestment risk can be reduced to some extent by constructing a well-researched bone portfolio, it is impossible to eliminate it. Hence, any significant decline in the market interest rates will likely impact bond investments, but the extent may vary across portfolios.

Recommended Articles

How Does Wait Function Work In Lua

Introduction to Lua wait.

The Lua wait is a function used when multiple processes simultaneously and want the primary process to stop for a given time. It is a method useful for stopping or delays the parent process until the child process is not working completely. It helps to reduce complications of the multiple processes at a time and work orderly. This function helps to stop or sleep parent thread for a minute, second, and millisecond and child thread within time. It helps to stop the parent thread for the child thread procedure and start the parent thread process after finish the child thread process. This method gives sleep time to work multiple thread procedures together without any critical issues.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of Lua wait

Given below is the syntax of Lua wait:

function wait(unit of time) Lua source codes for wait function… end wait(required time)

Explanation:

The “wait (unit of time)” is a method used to give the unit of time like a minute, second, and millisecond to stop the working procedure.

Example:

Code:

function wait ( millisecond ) end

The source code assigns the time to thread procedure for multiple operations.

The wait function delays the time in the millisecond using syntax example.

The wait (required time) is a function using forgiven time as per the user’s requirements.

Example:

wait( 1 )

The wait function is to stop the time to parent thread for one (1) millisecond.

How does wait Function Work in Lua?

Step 1: Lua programming IDE Environmental Setup.

The Lua text editor, Lua compiler, and Lua interpreter install in your computer as per the operating system and software version.

Or

It does not have software; then, you can use Lua Online IDEs for coding and start Lua programming.

Step 2: Create the Lua File.

The Lua file creates with the .lua extension and writes a source code.

Step 3: Creates the wait function with the time unit argument.

Code:

function wait(millisecond) write a code for the Lua wait function… end

Step 4: Create a variable with the operating system time.

Code:

local ostime_vrbl = os.time()

Step 5: Print the running time of the system.

print( "timing of Lua wait function: ", ostime_vrbl );

Step 6: Create a Lua wait method with the given time.

Code:

wait(0.5);

Combine the procedure of the Lua waits for demo example.

Code:

function wait(millisecond) local ostime_vrbl = os.time() print( "timing of Lua wait function: ", ostime_vrbl ); end wait(0.5); Examples of Lua wait

Given below are the examples mentioned:

Example #1

The Lua wait function with millisecond example and output.

Code:

function wait(millisecond) local ostime_vrbl = os.time() + millisecond print( "timing of Lua wait function: ", ostime_vrbl ); end wait(0.5); wait(1); wait(1.5); wait(2); wait(2.5); wait(3);

Output:

The example is using a millisecond unit of time for function.

Example #2

Function with the second example and output.

Code:

function wait(second) local ostime_vrbl = os.time() + second print( "timing of Lua wait function: ", ostime_vrbl ); end wait(1); wait(1.5); wait(2); wait(3); wait(4); wait(5);

Output:

Explanation:

The example is using the second unit of time for function.

Example #3

Function with millisecond and second Example and output.

Code:

function wait(second, millisecond) local ostime_vrbl = os.time() + second, millisecond print( "timing of Lua wait function: ", ostime_vrbl ); end wait(1, 2); wait(1, 0.5); wait(2, 1); wait(3, 0.7); wait(4); wait(5, 0);

Output:

Explanation:

The example is using the second and millisecond unit of time for function.

If we use two units of time, then the user either uses both time units or a single time unit.

Example #4

Lua wait function with “do while” condition example and output.

Code:

function wait(second, millisecond) local ostime_vrbl = os.time() + second, millisecond; while os.time() < ostime_vrbl do end print( "timing of Lua wait function: ", ostime_vrbl ); end wait(1, 2); wait(1, 0.5); wait(2, 1); wait(3, 0.7); wait(4); wait(5, 0);

Output:

Explanation:

The example is using the second and millisecond unit of time for the Lua wait function.

The Lua wait function is using the “do while” condition for comparison time.

If the operating system time is less than the given time, then the wait function works.

Example #5

Code:

function wait(second, millisecond) local ostime_vrbl = os.time() +  millisecond; repeat until os.time() < ostime_vrbl print("timing of Lua wait function: ", ostime_vrbl); end wait(1, 2); wait(1, 0.5); wait(2, 1); wait(3, 0.7); wait(4, 1); wait(5, 0);

Output:

Explanation:

The example is using the second and millisecond unit of time for the Lua wait function.

It is used milliseconds to return the time value.

This function is using the “repeat” condition for comparison time.

If the operating system time is less than the given time, then the wait function works.

Example #6

Function with compares time and variable example and output.

Code:

function wait(second, millisecond) local ostime_vrbl = os.time() + second, millisecond; print( "timing of Lua wait function: ", ostime_vrbl ); end wait(1, 2); wait(1, 0.5); wait(2, 1); wait(3, 0.7); wait(4); wait(5, 0);

Output:

Explanation:

The example is using the second and millisecond unit of time for the Lua wait function.

The Lua wait function is using the “do while” condition for comparison time.

If the operating system time is greater than the given time, then the wait function works.

Example #7

Lua waits with zero second example and output.

Code:

function wait(second, millisecond) local ostime_vrbl = os.time() + second, millisecond; while os.time() < ostime_vrbl do end print( "timing of Lua wait function: ", ostime_vrbl ); end wait(0);

Output:

Explanation:

The example is using the second and millisecond unit of time for the function.

The wait method does not use empty or nil values until an error occurred.

The user must give zero (0), millisecond, second, or minute inside for the wait method.

Conclusion

The Lua wait function helps to avoid complications of multiple operations. This function makes easy, elegant, and sophisticated applications. This function makes a fast, error-free application.

Recommended Articles

We hope that this EDUCBA information on “Lua wait” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does Subroutine Function Work In Perl?

Introduction to Perl Subroutine

Perl Subroutine is used to reusable code using a subroutine that we can use code, again and again, there is no need to repeatedly write the code. We can create our own functions it is called a subroutine. Subroutines are very important to improve the code reusability. It is also used to improve the code readability, using subroutine we can improve the code readability of our program. To use subroutine in our program we need to define or need to create it first, after creating then we call a subroutine in our code.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of Perl Subroutine

1. Defining a subroutine: To use subroutine in our program we need to create it first and then we need to call in our program. Below syntax shows define or create a subroutine in perl are as follows.

Syntax:

Sub subroutine_name  -- Name of subroutine that we have defining. { Statements;    -- Statement to be used in body of the subroutine. Return; }

2. Calling Subroutine: In perl we calling subroutine by passing a list of arguments. Below syntax shows calling a subroutine in perl are as follows.

Syntax:

subroutine_name (arguments_list); -- List of arguments which was used with subroutine. Parameters of Perl Subroutine

Below is the parameter description syntax of the subroutine in Perl is as follows.

Subroutine Name: It is very important while creating subroutine. We have defined any name to subroutine while creating the same. The subroutine name is the name that we have defined to the subroutine.

Statement: The statement is defined as a block or body of the code of subroutine. This code is written under the body of the subroutine. We can define one or more statement in the body of the subroutines.

Return: This is defined as the return an argument to its calling functions or subroutines. We can return no of arguments to the calling function in perl.

Argument List: This is defined as arguments which we have used at the time of calling a subroutine in Perl. We have pass one or more arguments at the time of calling a subroutine in Perl.

How Does Subroutine Function work in Perl?

Below is the working of the subroutine is as follows. Below is the important use of subroutine in perl.

Reusability of code.

Improve the code readability.

The subroutine is used to improve code reusability. If we want to take input from the user multiple times at the same time we have creating subroutine and then we call the subroutine in our program whenever we need it.

We can improve the code reusability while using the subroutine in our program. After using subroutine there is no need to write it again and again.

We can create our own functions it is called subroutines.

To use subroutine in our program we need to define or need to create it first, after creating then we call the same in our code.

It is used to reusability of code using subroutine we can use code, again and again, there is no need to write the code again and again.

It is also used to improve the code readability, using subroutine in perl we can improve the code readability of our program.

Subroutines is very important and useful to improve code reusability and readability.

It or function is a group or statement that used together to perform a task. We can divide our code into separate subroutines.

To divide subroutine into separate subroutines is depends on the developer but we can divide it logically based on the function which performed a specific task.

In the subroutine, function and method are the same but in other languages this is different.

The subroutines are used in perl programming language because subroutine in Perl created by using sub keyword.

When we have called to function or subroutines in our program, perl compiler will stop its all executing program and goes to execute the function to execute the same and then return back to execute the remaining section code.

We have avoided this by using the return statement in our program.

Examples

Below is the example of the subroutine in Perl is as follows.

Example #1

Passing Arguments to Subroutine: Below example shows passing arguments to a subroutine.

Code:

# Defining function in perl. sub Average { # Dispay number of arguments. $number = scalar(@_); $sum_of_num = 0; foreach $item (@_) { $sum_of_num += $item; } $average_of_num = $sum_of_num / $number; print "Average of numbers : $average_of_numn"; } # Calling function average to define average of given numbers. Average(100, 200, 300, 400, 500);

Example #2

Passing List to Subroutine: Below example shows passing a list to a subroutine.

Code :

# Defining function in perl with list as arguments. sub sub_PrintList { my @sub_list = @_; print "Given list @sub_listn"; } $p = 1; @q = (2, 3, 4, 5, 6, 7, 8, 9, 10);  ## Provide list as user input. # Function call with list parameter sub_PrintList($p, @q);

Output:

Example #3

Passing Hashes to Subroutine: Below example shows passing a hashes to a subroutine. In the below example, we have to pass the hashes to the subroutine.

Code:

# Defining function in perl with hashes as arguments. sub sub_PrintHash { my (%sub_hash) = @_; foreach my $key ( keys %sub_hash ) { my $hash_value = $sub_hash{$key}; print "$key : $hash_valuen"; } } # Function call with hashes parameter sub_PrintHash(%sub_hash);

Example #4

Returning Value from a Subroutine: The below example shows returning a value from a subroutine. In the below example, we have to return value from a subroutine.

Code:

# Defining function in perl. sub Average { $number = scalar(@_); $sum_number = 0; foreach $item (@_) { $sum_number += $item; } $average_num = $sum_number / $number; return $average_num; } # Function call $num = Average(10, 20, 30, 40, 50, 60, 70, 80, 90, 100); print "Average for numbers : $numn";

Output:

Conclusion

In perl we can create our own functions it is called as subroutines, subroutines is very important to improve the code reusability. It is used to reusability of code using subroutine we can use code again and again, there is no need to write the code again.

Recommended Articles

We hope that this EDUCBA information on “Perl Subroutine” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Map Function Works In Kotlin With Examples?

Introduction to Kotlin Map

Web development, programming languages, Software testing & others

Syntax

The kotlin language used many features as similar to java like collection, util package and even other packages classes and its method behaviours are the same as java. A map is one of the interfaces that can hold the datas as key-value pairs like java.

{ —–some coding logics it depends upon the application requirement— }

The above codes are the basic syntax for utilising the map interface on the kotlin. The mapping interface uses any type like Integer, String, Characters as the parameter type.

How does Map Function work in Kotlin?

A map is an interface that is used for to store the datas as the key-value pairs. Like java, it can be of the same type and feature. It’s worked in the kotlin. The key is the unique one, and it holds only a single value for each key; it also different pairs and combined with each other. It is the immutable one, and it is the fixed size, so after declaring the mapping size, it cannot be changed both static and dynamic. The members from the map interface are readable ones, so we cant edit and changeable for that. If we use the mutablemap interface, it supports both read and write access.

The key type is the invariant one, and it is accepted as the parameter; it uses a method like containsKey() and also it returns the keys set. Like that map value also covariant and its value type it also be changed if it’s required. The classes used on the map interface will be of any type; this is because of the classes used internally on the kotlin package. The map is of any type in the kotlin language; the key and value elements will be stored as a separate index; it takes the predicate arguments, the filter conditions will be of the negative type, and the key will be unique and it has many values.

Examples of Kotlin Map

Given below are the examples of Kotlin Map:

Example #1

Code:

package one; { val map = mapOf(1 to "Siva", 2 to "raman" , 3 to "Welcome", 4 to "To", 5 to "My Domain", 12 to "Its the twelth index and key value", 13 to "Its the thirteen index and key value", 14 to "Its the fourteen index and key value", 15 to "Its the fifteen index and key value") println( map) println("Its the first example for reagrding the kotlin map interface we used different classes and methods that can be related to the interface") val map1 = mapOf(6 to "Have a Nice Day users", 7 to "Its the Seventh index and key value" , 8 to "Its the eigth index and its key value", 9 to "Its the ninth index and its key value", 10 to "Its the tenth index and its key value", 11 to "Its the eleventh index and its key value") println("Thank you users for to spenting the time with our application your entries are : "+map1) println("Its the keys entries and it is used to store the variable : "+map1.keys ) println("Its the values the entries are used to store as the separate variable "+map1.values ) }

Output:

In the above example, we used a map interface, and it will store the user inputs as key-value pairs. We can use mapOf() method for to set the key values and print them accordingly.

Example #2

Code:

package one; { val first = mapOf("siva" to 1, 1 to "raman", 'A' to "Welcome To My Domain", "Have a Nice Day Users" to 'A') for ((k,v) in first) { println("Your input key is: $k and your input value is $v") } println("Your input key is: $k and your input value is $v") } println("Your input map size is: ${third.size}") println("Your input entries are: ${third.entries}") println("Your input key is: ${third.keys}") println("Your input values are: ${third.values}") println("Your Employeed ID is: ${third.get("Employee ID")}") println("Your Serial No is: ${third["SNO"]}") println("Your proofs are: ${third.getValue("ProofID")}") println("Your Employeed ID contains: ${third.containsKey("Employee ID")}") println("Your Serial No contains: ${third.contains("SNO")}") println("Your ProofID contains: ${"Chemistry" in third}") println("If any of the columns or attributes missing please add it separately: ${third.containsValue(1234566)}") println("The Additional or Missing attribute inputs are: ${third.getOrDefault("pincode",600063)}") }

Output:

Example #3

Code:

package one; { val third = mutableMapOf("Employee ID" to 1, 2 to "Employee Name", 3 to "Address", 4 to "City", 5 to "pincode") println(third) println(four) five.put("zipcode", 27346) println(five) five["SNo"] = 1234 println(five) five.putIfAbsent("landline", 91) five.putIfAbsent("MobileNumber", 2436) println(five) five.replace("Employee ID", 1) println(five) five.replace("Employee Name", 2, 3) println(five) five.remove("Address") println(five) five.remove("City", 4) println(five) five.clear() println(five) }

Output:

In the final example, we used a mutable map interface for to store the user inputs on key-value pairs. We used additional methods like remove(), replace(), clear() etc for to perform the operations.

Conclusion

In kotlin, we used a lot of collection util packages for to store, extract and retrieve the datas. Based on the requirements, we used specific util packages like map, list in a map we used a different set of interfaces and its methods for to implement the application which depends on the user requirements.

Recommended Articles

This is a guide to Kotlin Map. Here we discuss the introduction, syntax, and working of the map function in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –

How Sort() Algorithm Function Work In C++

Introduction to C++ sort()

The sort() function in C++ sorts a number of elements or a list of elements within the first to last elements in an ascending or descending order. This function executes the sorting operation within the specified list or range, starting with the first element and ending with the last element. The sort function takes in two parameters as arguments and returns the result of sorting. Comparing the elements is the main operation. There can be exceptions in case the elements that are being compared encounter any exceptions. The most common ways to sort are in either an ascending order or a descending order.

Start Your Free Software Development Course

Syntax and parameters:

The standard syntax for the sort function includes of sort keyword and two parameters. The return output will be the result of the sort operation.

void sort(RIt first, RIt last);

The parameters implemented in the above syntax are RandomIt, first and last.

Here the first and last are the range between whose sorting is to be done; the first notifies the first element of the list, while the last denotes the last element.

How sort() Algorithm Function work in C++?

The basic method by which the sorting algorithm works is based on comparison.

The sorting function attempts to compare each and every element of the list.

The comparison works in a way as comparing the first element with the second element, followed by the second and third, and so on. Here the comparison operator “<” is widely used.

So, simply speaking, the sort function at a time picks two values or elements of a list, then compare these two values to identify smaller and bigger value and arrange them in a form, ascending or descending, whichever is required.

Examples of C++ sort()

We will have a list of values, which will be unsorted and not in any order, and we will aim to correct the list by implementing the sort function.

Example #1

Our first example takes in an array of number values, unsorted, and we will implement the sort, and the output will be a list of values in a sorted format.

Code:

using namespace std; int main() { int arr1[] = {99,91,94,96}; int n = sizeof(arr1)/sizeof(arr1[0]); sort(arr1, arr1+n); cout << “n List of Array after sorting is: “; for (int i = 0; i < n; ++i) cout << arr1[i] << ” “; return 0; }

Explanation:

We have our system files and namespace, followed by initializing the main code. Then we have our first array variable of integer type, which holds a list of four numbers totally unsorted, following no order.

Then we have another integer variable followed by the sort function. We then print s statement, which then comes in our for statement, which will pick and print the numbers in a sorted format.

Upon successful execution, the output of the program will be a statement and a list of four numbers in a sorted format.

Output:

As explained and expected, the program generates an output statement followed by the corrected and sorted list of numbers. The sorting operation is performed in ascending order.

Example #2

Code:

using namespace std; void show(int a[]) { for(int b = 0; b < 10; ++b) cout << a[b] << ” “; } int main() { int a[10]= {3,4,1,0,5,7,8,6,9}; cout << “n This is the unsorted list: “; show(a); sort(a, a+10); cout << “nn Here’s the output of sort operation:: “; show(a); return 0; }

Explanation:

Started with required system files followed by declaring the login for the program. Then we have our main block of code, where we have an array with integer values followed by a print statement.

Then we have our sort function and parameter values passed, followed by the print statement and the final output.

The expected output is two statements, which include a list of the unsorted array and another list which is the output of the sorting operation.

Output:

Our code executed as expected, and the output is proper.

Example #3

Code:

int main() { std::cout << ‘n’; std::cout << “Sorting done with simple < operator: “; std::cout << ‘n’; std::sort(list.begin(), list.end()); for (auto a : list) { std::cout << a << “  “; } std::cout << ‘n’; std::cout << “n This is output of sorting using custom function: “; std::cout << ‘n’; struct { bool operator()(int a, int b) const { return a < b; } } customLess; std::sort(list.begin(), list.end(), customLess); for (auto a : list) { std::cout << a << ” “; } std::cout << ‘n’; }

Explanation:

Like the earlier example, we begin with the required system files and a main block. Then we have our array of values, followed by a few lines of code for output, where we first print the sorted list as a result of our sort operation. Then within our second method, we have a custom function, which creates a struct and passes the values.

Then we have our sort function, which starts with begin, then the end, and the custom function.

Output:

As expected, the output of the code is that the sorting has been done in two different formats using two methods.

Conclusion

In C++, we use the sort() function to sort a list of values. This function allows us to perform sorting in either ascending or descending order. We saw a few methods and ways to implement the sort function.

Recommended Articles

This is a guide to C++ sort(). Here we discuss the introduction to C++ sort(), how sort() algorithm function works, along with programming examples. You may also have a look at the following articles to learn more –

Update the detailed information about How Does Collect Function Work In Scala With Examples on the Cattuongwedding.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!