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.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Programming MCQs
- Apply for C++ Internship
- Check Programming Books
- Apply for Computer Science Internship
- Check C++ Books