temp

Sep 30, 2010 at 1:11am
Can someone help me start this code. I need to write the following function using templates and put it in functions.h which i havent created it :( i just need some help starting it:

myswap(A, B) — swap the value from A to B and B to A, so that afterwards, A and B are swapped

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <assert.h>
#include "functions.h"

using namespace std; 

#define ARRLEN 6

int main(int argc, char *argv[])
{
    
    int x, y; 
    double a, b;

    int iarr[] = {42, 42, 42, 56, 65, 99};
    float farr[] = {3.14, 3.14, 3.2, 4.5, 7.8, 0.0};
    
    x = 6; 
    y = 42; 

    a = 3.14159; 
    b = 3.14160; 
    
    assert(min(x,y) == x); 
    assert(min(a,b) == a);
    
    assert(count(iarr, y, ARRLEN) == 3);
    assert(count(farr, 3.14f, ARRLEN) == 2);

    assert(sum(iarr, ARRLEN) == 346);   
    assert(sum(farr, ARRLEN) == 21.78f);
    
    // Can't use *swap* because it's part of the STL
    myswap(x, y); 
    assert(x == 42);
    assert(y == 6); 
    
    myswap(a, b); 
    assert(a == 3.14160); 
    assert(b == 3.14159); 
    
    cout << "All tests passed!" << endl;

}

Last edited on Sep 30, 2010 at 1:13am
Sep 30, 2010 at 1:18am
So, you want to create a swap function, is that it?

You'll need to overload myswap() after you create it, and you'll need to pass by reference. Details on both can be found here, if you don't know about either of them:
http://cplusplus.com/doc/tutorial/functions2/

For the actual swap, I recommend having one temporary variable of the same type as the two arguments, assign one of the arguments' values to that, and then you should have no problems swapping the values.

-Albatross


Sep 30, 2010 at 5:21am
Hello,

If you are just trying to make it so the swap function can work on any type you can use:

1
2
3
4
5
template <typename T>
void mySwap(T a, T b)
{
     //implement your own swaping code here
}


Here is a template tutorial:
http://www.cplusplus.com/doc/tutorial/templates/

Hope that helped.
Sep 30, 2010 at 1:49pm
malgron: That doesn't help because it won't work. a and b have to be passed by reference, not by value.

1
2
3
4
template< typename T >
void mySwap( T& a, T& b )
{
}

Topic archived. No new replies allowed.