How to swap two variables using template in C++

2 Answers

0 votes
#include <iostream>

template<class T>
void swap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 10;
    int y = 25;
    
    swap(x, y); // swap<int>(x, y);

    std::cout << x << " " << y;
}




/*
run:

25 10

*/

 



answered Dec 5, 2022 by avibootz
0 votes
#include <iostream>
 
template<class T>
void swap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}
 
int main() {
    float x = 3.14;
    float y = 1.07;
     
    swap(x, y); // swap<float>(x, y);
 
    std::cout << x << " " << y;
}
 
 
 
 
/*
run:
 
1.07 3.14
 
*/

 



answered May 3, 2024 by avibootz

Related questions

1 answer 157 views
1 answer 136 views
1 answer 191 views
1 answer 243 views
1 answer 242 views
1 answer 98 views
1 answer 179 views
...