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.
/*
* C++ program to demonstrate the swap_ranges() algorithm
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
void print(int v)
{
std::cout << std::setw(2) << std::setfill('0')
<< v << " ";
}
int main()
{
int a[] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int b[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "Array a : ";
std::for_each(a, a + 10, print);
std::cout << std::endl;
std::cout << "Array b : ";
std::for_each(b, b + 10, print);
std::cout << std::endl;
std::swap_ranges(a + 2, a + 6, b + 2);
std::cout << "After swapping elements" << std::endl;
std::cout << "Array a : ";
std::for_each(a, a + 10, print);
std::cout << std::endl;
std::cout << "Array b : ";
std::for_each(b, b + 10, print);
std::cout << std::endl;
}
$ 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.
Related Posts:
- Check Programming Books
- Practice Computer Science MCQs
- Apply for C++ Internship
- Apply for Computer Science Internship
- Check C++ Books