swap values in two variables

Apr 25, 2011 at 3:52pm
Write a generic function that swaps values in two variables. Your function should have two parameters of the same type. Test the function with int, double and string values.

Was wondering if someone could give me some hints on where to even start. I don't really even know what the question is asking for. Thanks
Apr 25, 2011 at 4:01pm
It's just asking for you to write a function that will accomplish this:

before:
a = 12
b = 25
after:
a = 25
b = 12

but it has to work with any data type.
Apr 25, 2011 at 4:02pm
All you have to do is write a template function that swaps the value of two variables.
A template function looks like this:
1
2
3
4
5
template <typename T>
void swap(T& a, T& b)
{

}

Then you just have to swap them so that a = b and b = (original)a. The most common way to do it is to use a temporary variable:
1
2
3
c = a
a = b
b = c
Apr 26, 2011 at 1:21pm
alright i get the part about swapping the values but i'm not sure what it means by test the function with int, double, and string values.
Apr 26, 2011 at 1:34pm
closed account (zb0S216C)
i'm not sure what it means by test the function with int, double, and string values.
Note: I'm referring to Chrisname's code snippet.

It's relatively simple. You call the template method with the specified types such as:
swap < Type-Specifier > ( ..., ... ); Note: Where 'Type-Specifier' is either one your your target types.
Apr 26, 2011 at 1:58pm
I'm sorry but i'm not very good at this stuff and i'm still not sure what that means I'll show you what I have so far
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
template <typename T>
void swap(T n1, T n2)
{
     int temp=n1;
     n1=n2;
     n2=temp;
}


int main()
{
Apr 26, 2011 at 2:04pm
You need references (&) like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
template <typename T>
void swap(T &n1, T &n2) // Note the &
{
     T temp=n1; // Note use the type T
     n1=n2;
     n2=temp;
}


int main()
{
  int a = 2;
  int b = 3;
  swap(a, b); // Now a = 3 and b = 2

  double x = 2.3;
  double y = 4.5;
  swap(x, y); // Now x = 4.5 and y = 2.3
}
Last edited on Apr 26, 2011 at 2:04pm
Apr 26, 2011 at 2:05pm
ok Thanks for the example
Topic archived. No new replies allowed.