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.
/*
* C++ program to swap elements using iter_swap() algorithm
*/
#include <iostream>
#include <vector>
#include <algorithm>
void print(int v)
{
std::cout << v << " ";
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector <int> v(10);
std::cout << "Vector : ";
std::for_each(v.begin(), v.end(), print);
std::cout << std::endl;
std::cout << "Array : ";
std::for_each(a, a + 10, print);
std::cout << std::endl;
for (int i = 1; i < 10; i+=2)
std::iter_swap(v.begin() + i, a + i);
std::cout << "Swapping odd places of vector with odd places of array"
<< std::endl;
std::cout << "Vector : ";
std::for_each(v.begin(), v.end(), print);
std::cout << std::endl;
std::cout << "Array : ";
std::for_each(a, a + 10, print);
std::cout << std::endl;
}
$ 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