iter_swap() in C++

«
»
This C++ program demonstrates the iter_swap() algorithm. The creates an array and a vector of integers and swaps the elements at odd positions of vector and array. The elements of vector and array are then printed on standard output.

Here is the source code of the C++ program which demonstrates the iter_swap() 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 swap elements using iter_swap() algorithm
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7.  
  8. void print(int v)
  9. {
  10.     std::cout << v << "   ";
  11. }
  12.  
  13. int main()
  14. {
  15.     int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  16.     std::vector <int> v(10);
  17.  
  18.     std::cout << "Vector : ";
  19.     std::for_each(v.begin(), v.end(), print);
  20.     std::cout << std::endl;
  21.     std::cout << "Array  : ";
  22.     std::for_each(a, a + 10, print);
  23.     std::cout << std::endl;
  24.     for (int i = 1; i < 10; i+=2)
  25.         std::iter_swap(v.begin() + i, a + i);
  26.     std::cout << "Swapping odd places of vector with odd places of array"
  27.               << std::endl;
  28.     std::cout << "Vector : ";
  29.     std::for_each(v.begin(), v.end(), print);
  30.     std::cout << std::endl;
  31.     std::cout << "Array  : ";
  32.     std::for_each(a, a + 10, print);
  33.     std::cout << std::endl;
  34. }

$ a.out
Vector : 0   0   0   0   0   0   0   0   0   0   
Array  : 1   2   3   4   5   6   7   8   9   10   
Swapping odd places of vector with odd places of array
Vector : 0   2   0   4   0   6   0   8   0   10   
Array  : 1   0   3   0   5   0   7   0   9   0

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

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

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 & technical discussions at Telegram SanfoundryClasses.