iter_swap() in C++
Posted by Superadmin on August 10 2022 05:35:27

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