Templates Functions and Exceptions

I get an assertion error. What is wrong?

functions.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template <class T>

T myswap(T&a, T&b)
{
    
    T c=a;
      a=b;
      b=c;
}

template <class T>
T sum(T array1[], int arrlength)
{
    int i;
    for (i=0; i<arrlength; i++)
    {
        array1[i] = array1[i] + 1;
    }
} 

template <class T>
T count(T array2[], T value, int length)
{
}



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
45
#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);
 
  
    // cant 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;
    \
}

1
2
    assert(a == 3.14160); 
    assert(b == 3.14159); 


You can't shouldn't use == with floating point values. Floating points are approximations.

Here's more reading if you're interested:

http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17

(EDIT2: it might be okay to use it here since you're just doing assignments and no computations, but it's still a really bad idea)



Also, your sum() function doesn't sum anything... it just adds 1 to each element.

EDIT: actually the sum() problem is probably what's causing the assertion failure, since that is running first. So yeah -- fix your sum() function.
Last edited on
array1[i] = array1[i] + i;

it still shows assertion error.
that is still not summing the array. What you're doing there is adding 'i' to each element in the array.

This function should not be modifying array1. It should simply be totalling all the values in array1 and returning the total.
1
2
int sum = 0;
sum + array1[i]
??
Last edited on
Yeah that should work.
1
2
3
4
5
6
7
8
9
10
template <class T>
T sum(T array1[], int arrlength)
{
    int i;
    int sum=0;
    for (i=0; i<arrlength; i++)
    {
        sum= sum + array1[i];
    }
} 


I still get an assertion error. Mine looks exactly like tmoney91's. Have anyone tried to compile and get the error too? Thanks for the help so far.
Topic archived. No new replies allowed.