Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<assert.h>
- #include<string>
- #include<iostream>
- #include<vector>
- template<typename T> void swap(T& first, T& second){
- //with concepts we could specialize one version of the function to perform the XOR
- //based swap if the type has the operator
- T const temp = first;
- first = second;
- second = temp;
- }
- int main(){
- int i = 0;
- int j = 1;
- swap(i, j);
- assert(i==1 && j==0 && "Doesnt work for ints!");
- std::string s1 = "Hello";
- std::string s2 = "World";
- swap(s1, s2);
- assert(s2=="Hello" && s1 == "World" && "Doesnt work for strings!");
- std::cout << "It Works!\n";
- //Better, more idiomatic way...
- std::vector<int> v1 = {1,2,3,4};
- std::vector<int> v2 = {4,3,2,1};
- std::swap(v1, v2);
- std::cout << "using std::swap \nv1\n";
- for(auto const &e : v1){
- std::cout << e << " ";
- }
- std::cout << "\nv2\n";
- for(auto const &e : v2){
- std::cout << e << " ";
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment