This C++ program swaps elements of containers using swap() algorithm. The program initializes the elements of the container to be swapped, the containers are passed to the function by reference and the elements of the containers are swapped.
Here is the source code of the C++ program which swaps elements of two container using 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 of containers using swap() algorithm
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
void print(vector <string> vs)
{
vector <string>::iterator i;
for(i = vs.begin(); i != vs.end(); i++)
{
cout << left << setw(10) << *i;
}
cout << endl;
}
int main()
{
string sarr[] = {"Belarus", "Croatia", "Denmark", "Finland", "Bhutan", "China", "India", "Japan"};
int slen = sizeof(sarr) / sizeof(string);
vector <string> va(sarr, sarr + 4);
cout << "Asian Countries : ";
print(va);
vector <string> ve(sarr + 4, sarr + slen);
cout << "European Countries : ";
print(ve);
cout << "\nCountries are in wrong lists. They are to be swapped!" << endl;
swap(va, ve);
cout << "\nAsian Countries : ";
print(va);
cout << "European Countries : ";
print(ve);
cout << "\nNow they are in right lists!" << endl;
}
$ a.out Asian Countries : Belarus Croatia Denmark Finland European Countries : Bhutan China India Japan Countries are in wrong lists. They are to be swapped! Asian Countries : Bhutan China India Japan European Countries : Belarus Croatia Denmark Finland Now they are in right lists!
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for C++ Internship
- Buy Programming Books
- Apply for Information Technology Internship
- Buy C++ Books
- Apply for Computer Science Internship