Index of max in Array of doubles.

I have the following the code. The following is the fastest implementation I could think of for gettting the index of max element in an array. I want to use pointers for this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Function to find index of highest (maximum) value in array
int* IndexMaximumValue(double &nextAmount[])
{
     int length = sizeof(*nextAmount)/sizeof(int);  // establish size of array
     double max = *nextAmount[0];       // start with max = first element
     int* index = 0;

     for(int i = 1; i<length; i++)
     {
          if(*nextAmount[i] > max)
		  {  *max = *nextAmount{i};
		     *index = i;
		  }
     }
	 return &index;
}


Can someone please tell me where I'm going wrong with this?

Following are some of the errors I'm getting.


line 11 .... error C2234: 'nextAmount' : arrays of references are illegal
line 11 .... error C2440: '=' : cannot convert from 'double *' to 'double'


Also, would it matter whether I use vector or an array in terms of efficiency, if I'm sorting through a LARGE array?
You have some syntax errors but even if you didn't have them it still wouldn't work.
This -> int length = sizeof(*nextAmount)/sizeof(int); won't work. You must pass the size of the array as an argument. And why do you want to use pointers so badly? :D

If I were you, I'd do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int get_max_pos(double * array, int size)
{
    double max=array[0];
    int max_pos=0;

    int i;
    for (i=1; i<size; i++)
    {
        if (max<array[i])
        {
            max=array[i];
            max_pos=i;
        }
    }

    return max_pos;
}
I would consider using a std::vector rather than an array. Its an array on the inside and unlikely to be any slower that using an array.
You might also consider using a std::valarray which is designed just for this type of operation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <valarray>
#include <iostream>

int main()
{
	std::valarray<double> nextAmount(4);

	nextAmount[0] = 12.78;
	nextAmount[1] = 88.67;
	nextAmount[2] = 22.2;
	nextAmount[3] = 87.99;

	for(size_t i = 0; i < nextAmount.size(); ++i)
	{
		std::cout << "nextAmount[" << i << "] = " << nextAmount[i] << std::endl;
	}

	std::cout << "max: " << nextAmount.max() << std::endl;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.