C++ Forward_list Library - merge() Function


Advertisements

Description

The C++ function std::forward_list::merge() merges two sorted forward_lists into one.

Declaration

Following is the declaration for std::forward_list::merge() function form std::forward_list header.

C++11

template <class Compare>
void merge (forward_list& fwdlst, Compare comp);

Parameters

  • x − Another forward_list object of same type.

  • comp − A comparison function which should return true or false. It has following prototype.

bool comp(const Type1 &arg1, const Type2 &arg2);

Return value

None

Exceptions

This member function never throws exception.

Time complexity

Linear i.e. O(n)

Example

The following example shows the usage of std::forward_list::merge() function.

#include <iostream>
#include <forward_list>

using namespace std;

bool cmp_fun(int a, int b) {
   return a > b;
}

int main(void) {

   forward_list<int> fl1 = {31, 11, 5, 1};
   forward_list<int> fl2 = {30, 20, 10};

   fl2.merge(fl1, cmp_fun);

   cout << "List contains following elements" << endl;

   for (auto it = fl2.begin(); it != fl2.end(); ++it)
      cout << *it << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

List contains following elements
31
30
20
11
10
5
1
forward_list.htm
Advertisements