swap_ranges() Function in C++

This C++ program demonstrates the swap_ranges() algorithm. The program creates two arrays of integers and swaps the elements by passing iterators to the range of elements to be swapped into the function swap_ranges.

Here is the source code of the C++ program which demonstrates the swap_ranges() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ program to demonstrate the swap_ranges() algorithm
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <iomanip>
  8.  
  9. void print(int v)
  10. {
  11.     std::cout << std::setw(2) << std::setfill('0')
  12.               << v << "   ";
  13. }
  14.  
  15. int main()
  16. {
  17.     int a[] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
  18.     int b[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  19.  
  20.     std::cout << "Array a : ";
  21.     std::for_each(a, a + 10, print);
  22.     std::cout << std::endl;
  23.     std::cout << "Array b : ";
  24.     std::for_each(b, b + 10, print);
  25.     std::cout << std::endl;
  26.     std::swap_ranges(a + 2, a + 6, b + 2);
  27.     std::cout << "After swapping elements" << std::endl;
  28.     std::cout << "Array a : ";
  29.     std::for_each(a, a + 10, print);
  30.     std::cout << std::endl;
  31.     std::cout << "Array b : ";
  32.     std::for_each(b, b + 10, print);
  33.     std::cout << std::endl;
  34. }

$ a.out
Array a : 11   12   13   14   15   16   17   18   19   20   
Array b : 01   02   03   04   05   06   07   08   09   10   
After swapping elements
Array a : 11   12   03   04   05   06   17   18   19   20   
Array b : 01   02   13   14   15   16   07   08   09   10

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.