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.
/*
* 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
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Check Programming Books
- Check C++ Books
- Apply for C++ Internship
- Practice Programming MCQs
- Apply for Information Technology Internship