Guest User

Untitled

a guest
Oct 17th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include<assert.h>
  2. #include<string>
  3. #include<iostream>
  4. #include<vector>
  5.  
  6.  
  7. template<typename T> void swap(T& first, T& second){
  8. //with concepts we could specialize one version of the function to perform the XOR
  9. //based swap if the type has the operator
  10.  
  11. T const temp = first;
  12. first = second;
  13. second = temp;
  14. }
  15.  
  16. int main(){
  17. int i = 0;
  18. int j = 1;
  19. swap(i, j);
  20. assert(i==1 && j==0 && "Doesnt work for ints!");
  21.  
  22. std::string s1 = "Hello";
  23. std::string s2 = "World";
  24. swap(s1, s2);
  25. assert(s2=="Hello" && s1 == "World" && "Doesnt work for strings!");
  26. std::cout << "It Works!\n";
  27.  
  28. //Better, more idiomatic way...
  29. std::vector<int> v1 = {1,2,3,4};
  30. std::vector<int> v2 = {4,3,2,1};
  31. std::swap(v1, v2);
  32.  
  33. std::cout << "using std::swap \nv1\n";
  34. for(auto const &e : v1){
  35. std::cout << e << " ";
  36. }
  37.  
  38. std::cout << "\nv2\n";
  39. for(auto const &e : v2){
  40. std::cout << e << " ";
  41. }
  42.  
  43. return 0;
  44. }
Add Comment
Please, Sign In to add comment