removing elements from array

Ok so I am trying to figure out how to remove element from an array when it is dynamically allocated in the first place.

I have to remove the max and min value in the array in order to find the average of the remaining values. Originally I thought that just setting the max and min to 0 should work but for some reason I am getting errors whenever I get the index value of the min and max number. Seemed like a bad idea. Anyone help?


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
   int *scoreArray = NULL;
   scoreArray = new int[numOfJudges];

   for (int i = 0; i < numOfJudges; i++)
   {
	cin >> scores;
	scoreArray[i] = scores;
   }

   int min, max;
   max = scoreArray[0];

	for (int x = 1; x <= N; x++)
	{
		if (scoreArray[x] > max)
		{
			max = scoreArray[x];
			maxAddr = x;
		}
	}

	min = scoreArray[0];
	for (int z = 1; z <= N; z++)
	{
		if (scoreArray[z] < min)
		{
			min = scoreArray[z];
			minAddr = z;
		}
	}
   
 scoreArray[maxAddr] = 0;
 scoreArray[minAddr] = 0;
One problem is in your for loops. Indices start at 0 and end at size - 1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    std::vector<int> scoreArray(numOfJudges);
    // fil the vector with your values...
    
    // sort the values
    std::sort<>( scoreArray.begin(), scoreArray.end() );
    
    // remove the minimal and maximal value
    scoreArray.erase( scoreArray.end()-1);
    scoreArray.erase( scoreArray.begin());
    
    // calculate the average
    double average = 0;
    for( auto value : scoreArray) average += value;
    average /= scoreArray.size();

If you not familiar with the using of std::vector, I suggest that you do so. That's perhaps the most used container at c++ and displaces at most cases the built-in arrays.
Last edited on
You don't need to remove the max and min to find the average of the remaining values. Just subtract them from the full sum and divide by two less than the full size of the array.

averageModified = ( sum - maxNum - minNum ) / ( N - 2 );

That would save you having to sort them and modifying or erasing any element of the array, and you can compute sum, maxNum and minNum in a single loop.
Thank you for all the help.!!
Topic archived. No new replies allowed.