Finding the Index/position of Min and Max

I am looking for some assistance on my code. Right now I have to take a text file with a first name, last name, and the number of movies they have seen. I have all my variables defined in the main function and all the math and reading of the code in other functions. I have three separate arrays, fName, lName, arr (which holds the number of movies) Right now I am struggling. I need to be able to find the index, or position of the min and max in the arr array. This is the code I have so far, remember, everything is declared and already used in the main function (except for position)

1
2
3
4
5
6
7
8
9
10
11
12
13
void minAndMaxFunction(int arr[], string fName[], string lName[], int& min, int& max, int siz, int position) {
  for (int i = 0; i < siz; i++) {
		
		if (min > arr[i]) {
			min = arr[i];
	
		}

		if (arr[i] > max) {
			max = arr[i];
		}
}


The min and max come out correctly but I need to figure out where in the arr they are stored like min is technically stored in line 8, arr index 7 and max is stored on line 9 index 8. How do I go about doing this?
Last edited on
Hello Annamarie0408,

Without the rest of the program I am guessing a bit here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void minAndMaxFunction(int arr[], string fName[], string lName[], int& min, int& max, int siz, int& minPosition, int& maxPosition)
{
	for (int i = 0; i < siz; i++)
	{

		if (min > arr[i])
		{
			min = arr[i];
			minPosition = i;
		}

		if (arr[i] > max)
		{
			max = arr[i];
			maxPosition = i;
		}
	}

This should give you an idea of what needs done. And when you think about it you only need array "arr" here. The other two are not used here.

Hope that helps,

Andy
There are many things that one could know and learn.

One is to know what tools the Standard Library has and when to use them.
There happens to be:
http://www.cplusplus.com/reference/algorithm/minmax_element/
http://www.cplusplus.com/reference/iterator/distance/

Another is to see an idea within implementation and to understand enough C++ syntax to be able to adapt the code to similar task. For example, from:
http://www.cplusplus.com/reference/algorithm/min_element/

Finally, the ability to produce the logical steps that will lead to a correct solution.


Can you tell how code on std::min_element's page differs from Andy's version?
It's usually more flexible to return an index (or an iterator) instead of the actual element:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Assumes that siz != 0
void minAndMaxFunction(int arr[], string fName[], string lName[], int& minIdx, int& maxIdx, int siz) {
  minIdx = maxIdx = 0;
  for (int i = 1; i < siz; i++) {
		
		if (arr[minIdx] > arr[i]) {
			minIdx = i;
	
		}

		if (arr[i] > arr[maxIdx]) {
			maxIdx = i;
		}
}
Topic archived. No new replies allowed.