set operator= in C++ STL

C++Server Side ProgrammingProgramming

The function operator= is used in sets to copy one set (or move to another in C++ STL. It behaves as a normal ‘=’ assignment operation for sets. There are there overloaded forms of this function −

  • copy :- set& operator= (const set& s1)

    This function copies all the elements in set s1 to another set. The parameter passed is set of the same type.

  • Usage − set s1=s2;

  • move :- set& operator=( set &&s1 )

    This moves the elements of set s1 into the calling set.

  • Initializer list :- set& operator= (initializer_list<value_type> ilist)

    This version copies the values of the initializer list ilist into the calling set.

    Usage − set<int> s1= { 1,2,3,4,5 };

Note − All of them return the reference of this pointer of set<T> type.

Following program is used to demonstrate the usage of round function in a C++ program −

Example

 Live Demo

#include <iostream>
#include <set>
using namespace std;
// merge function
int main(){
   set<int> set1, set2;
   // List initialization
   set1 = { 1, 2, 3, 4, 5 };
   set2 = { 10,11,12,13 };
   // before copy
   cout<<"set1 :";
   for (auto s = set1.begin(); s != set1.end(); ++s) {
      cout << *s << " ";
   }
   cout << endl;
   cout<<"set2 :";
   for (auto s = set2.begin(); s != set2.end(); ++s) {
      cout << *s << " ";
   }
   //after copy set1 to set2
   cout<<endl<<"After Copy"<<endl;
   cout<<"set1 :";
   set1=set2;
   for (auto s = set1.begin(); s != set1.end(); ++s) {
      cout << *s << " ";
   }
   return 0;
}

Output

set1 :1 2 3 4 5
set2 :10 11 12 13
After Copy
set1 :10 11 12 13
raja
Published on 28-Jul-2020 14:16:41
Advertisements