C++ Multimap Non Member Swap Function - C++ Programming Tutorial
C++ Course / STL Set & Map / C++ Multimap Non Member Swap Function

C++ Multimap Non Member Swap Function

BLUF: Mastering C++ Multimap Non Member Swap Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Multimap Non Member Swap Function

C++ is renowned for its efficiency. Learn how C++ Multimap Non Member Swap Function enables low-level control and high-performance computing in the tutorial below.

In C++, the multimap data structure is included in the Standard Template Library (STL) and enables the storage of numerous key-value pairs, permitting the existence of multiple elements sharing the same key.

C++ swap serves as a non-member function of multimap in the C++ programming language. It is frequently employed to interchange (or switch) the data of two multimaps (referred to as x and y), with the condition that both multimaps are of identical types, despite potential differences in sizes. This operation effectively exchanges all elements, sizes, and internal data of the two multimaps without the need for duplicating or relocating each element individually.

It enhances the efficiency of the swap method, particularly with extensive multimaps, as it operates with a constant time complexity (O(1)) by directly swapping the internal pointers of the containers.

Syntax:

It has the following syntax:

Example

template <class Key, class T, class Compare, class Alloc>

   void swap (multimap<Key,T,Compare,Alloc>& lhs, multimap<Key,T,Compare,Alloc>& rhs);

In this particular format,

  • lhs denotes the object on the left side within the multimap.
  • rhs signifies the object on the right side with the identical type in the multimap structure.
  • Return Value:

It does not provide any output. It solely returns void.

Complexity:

It has a constant-time complexity, i.e., (O(1)).

C++ Simple Multimap swap Function

Let's consider a scenario to demonstrate the swap function for multimap in C++.

Example

Example

#include <iostream>  

#include <map>  

  

using namespace std;     //using standard namespace

  

int main(void) {     //main function

   multimap<char, int> m1 = {  

      {'a', 1},  

      {'b', 2},  

      {'c', 3},  

      {'b', 4},  

      {'e', 5},  

      };  

  

   multimap<char, int> m2;  

  

   swap(m1, m2);  

  

   cout << "Multimap contains the following elements" << endl;  

  

   for (auto it = m2.begin(); it != m2.end(); ++it)  

      cout << it->first << " = " << it->second << endl;  

  

   return 0;  

}

Output:

Output

Multimap contains the following elements

a = 1

b = 2

b = 3

c = 4

e = 5

Explanation:

In this instance, we showcase the application of the non-member swap function with a C++ multimap. Initially, we set up the multimap m1 with entries that have duplicate keys, while the second multimap m2 remains void of elements. Upon executing swap(m1, m2), the process completes in constant time, moving the contents of m1 into m2. Consequently, m1 will be devoid of elements, while m2 will encompass all the elements previously in m1. To demonstrate this exchange, the program utilizes an iterator to display the contents of m2.

Key Features of the multimap swap Function in C++

There are several features of the multimap swap function in C++. Some of them are as follows:

  • The swap function is commonly utilized to exchange the elements and related properties (such as comparator and allocator) of two multimaps in constant time without each element copying or moving.
  • The swap function is more efficient than copying elements because it will only swap internal pointers instead of deep copying each element.
  • It will not throw an exception. It is safe for its intended high-level use and is common for the STL.
  • It is very useful to quickly replace or clear large multimaps without performing expensive copy operations.
  • It helps to maintain the order of elements inside every multimap.
  • Swapping the Contents of Two Multimaps Using the swap function in C++

Let's consider a scenario to demonstrate the process of exchanging the data of two multimaps by utilizing the swap function in the C++ programming language.

Example

Example

#include <iostream>  

#include <map>  

  

using namespace std;     //using standard namespace

  

int main ()    //main function

{  

  multimap<char,int> multimap1,multimap2;  

  

  multimap1 = { {'x', 100},  

                {'y', 200}  };  

  

  multimap2= { {'a', 110},  

               {'c', 220},  

               {'c', 330} };  

  

  swap(multimap1,multimap2);  

  

  cout << "Multimap1 contains element:\n";  

  for (multimap<char,int>::iterator it=multimap1.begin(); it!=multimap1.end(); ++it)  

    cout << it->first << " => " << it->second << '\n';  

  

  cout << "Multimap2 contains element:\n";  

  for (multimap<char,int>::iterator it=multimap2.begin(); it!=multimap2.end(); ++it)  

    cout << it->first << " => " << it->second << '\n';  

  

  return 0;  

}

Output:

Output

Multimap1 contains element:

a => 110

c => 220

c => 330

Multimap2 contains element:

x => 100

y => 200

Explanation:

In this instance, we've established two multimaps (multimap1 and multimap2) containing distinct key-value pairs upon initialization. Subsequently, the swap method is employed to switch their contents. Following the completion of the swapping process, all elements originally in multimap1 transfer to multimap2, and vice versa. Ultimately, both multimaps display their contents, now effectively exchanged.

Swapping Two Multimaps Using a Template Print Function in C++:

Let's consider a scenario to demonstrate the process of exchanging two multimaps by utilizing a template print function in C++.

Example

Example

#include <iostream>  

#include <map>    

using namespace std;    //using standard namespace

template <class Multimap>  

void print(const char* name, const Multimap& m)  

{  

  cout << name << " : {";  

  for (const auto& x : m) {  

    cout << "[" << x.first << "," << x.second << "]";  

  }  

  cout << "}" << endl;  

}  

  

int main()    //main function

{  

  multimap<int, char> m1;  

  m1.insert(std::make_pair(10, 'a'));  

  m1.insert(std::make_pair(20, 'b'));  

  m1.insert(std::make_pair(10, 'c'));  

  

  multimap<int, char> m2;  

  m2.insert(std::make_pair(5,  'd'));  

  m2.insert(std::make_pair(15, 'e'));  

  

  

//Swap m1 and m2  

  swap(m1, m2);  

  

  print("m1", m1);  

  print("m2", m2);  

}

Output:

Output

m1 : {[5,d], [15,e]}

m2 : {[10,a], [10,c], [20,b]}

Explanation:

In this instance, we've established two multimaps known as m1 and m2. The m1 multimap is set up with the key-value pairs {(10,'a'), (20,'b'), (10,'c')}, while m2 is set up with key-value pairs {(5,'d'),(15,'e')}. Following this, executing the swap(m1,m2) function will interchange the contents of the two multimaps instantaneously, resulting in m1 containing the former contents of m2, and vice versa.

C++ Example for multimap::swap and clear Functions:

Let's consider an instance to demonstrate the swap method of multimap along with the clear function in C++.

Example

Example

#include <iostream>  

#include <string>  

#include <map>  

  

using namespace std;    //using standard namespace

  

void show(const char *msg, multimap<string, int> mp);  

  

int main() {     //main function

  multimap<string, int> m1, m2;  

  

  m1.insert(pair<string, int>("A", 100));  

  m1.insert(pair<string, int>("G", 300));  

  m1.insert(pair<string, int>("B", 200));  

  

  // Exchange the contents of m1 and m2.  

  cout << "Exchange m1 and m2.\n";  

  swap(m1,m2);  

  show("Contents of m2: ", m2);  

  show("Contents of m1: ", m1);  

  

 // Clear m1.  

  m1.clear();  

  if(m1.empty()) cout << "m1 is now empty.";  

  

  return 0;  

}  

  

// Display the contents of a multimap<string, int> by using an iterator.  

void show(const char *msg, multimap<string, int> mp) {  

  multimap<string, int>::iterator itr;  

  

  cout << msg << endl;  

  for(itr=mp.begin(); itr != mp.end(); ++itr)  

    cout << "  " << itr->first << ", " << itr->second << endl;  

  cout << endl;  

}

Output:

Output

Exchange m1 and m2.

Contents of m2:

A, 100

B, 200

G, 300

Contents of m1:

m1 is now empty.

Explanation:

In this instance, we've established two multimaps, m1 and m2, with predefined key-value pairs. Subsequently, the swap method is employed to efficiently interchange their contents, effectively transferring all elements from m1 to m2 and vice versa. Following the swap operation, the display method is invoked to exhibit the contents of both multimaps. Lastly, we employed the clear method on m1 to eliminate all its elements, and the empty method confirms that m1 is currently devoid of any elements.

Conclusion

In summary, the swap function in C++ for multimaps is a straightforward and effective technique for exchanging the data within two multimaps. This function operates efficiently with a constant time complexity (O(1)) by internally swapping the data structures. It proves to be beneficial when dealing with extensive datasets as it reduces redundancy and unnecessary performance costs. Overall, the swap function enhances the management of multimaps by boosting both flexibility and performance.

C++ multimap non-member swap function FAQ's

The non-member swap function in a multimap exchanges the contents of two multimap containers.

In the C++ coding language, the multimap swap method is employed to exchange the elements of two multimaps efficiently by interchanging their internal data structures.

How does the non-member swap operation differ from the member swap function?

Even if both exchanges carry out the identical task, the non-member swap serves as a standalone function that symmetrically operates on the two containers, whereas the member swap is invoked on a single container instance.

3) What type of operations does the swap function carry out on multimaps in C++ - copying or moving?

No, the swap method exchanges the internal structures of the containers, making it more efficient than copying or moving elements one by one.

After the swap operation in C++, the multimaps undergo a complete exchange of their elements, resulting in each multimap containing the elements that were originally in the other multimap. This swapping process does not involve any deep copy or modification of the elements themselves; instead, it simply exchanges the internal data structures of the multimaps to achieve the desired outcome.

After executing the swap operation, the contents have been completely interchanged, resulting in each multimap now holding the elements originally present in the other multimap.

5) Is it possible for exceptions to be thrown when utilizing the swap function with multimaps?

In broad terms, the swap method operates in constant time and does not raise exceptions when employed with multimaps.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience