Vector algorithm

hey forum,

I'm really stuck in this one. For my function I need to find the highest, 2nd highest, 3rd highest and lowest from a vector with 4 ints. Am I missing something and is this actually really easy? I tried yet with the max() function etc but no succes...
Please do give the code, but just the concept so I can work it out myself..

thank you!
The best way would probably be to sort the vector, but I have a feeling that you're supposed to find them the hard way.
pseudocode:
int max_i = -1
for each int i < vector.size
if max_i == -1 || vector[max_i] < vector[i] then max_i = i

You can then either remove element max_i form vector or add something like
if i == prev_max_i then continue
to the next for loop.
I can't sort indeed...
I'll try what you coded there, thanks

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
#include <iostream>
#include <string>
#include <algorithm>

//#include "../../std_lib_facilities.h"



int main()
{
	cout << "Enter 3 numbers:" << std::endl;
	vector<int> v;
	int n = 0;
	while(v.size() < 3 && std::cin >> n )
	{
		v.push_back(n);
	}
	std::sort(v.begin(), v.end());

	for(vector<int>::size_type i = 0; i < v.size(); ++i)
	{


		std::cout << " " << v[i] << " ,";

	
	}

	keep_window_open();
}
Last edited on
L E G I O N, I can't switch the vectors around
A mathematical description of the solution:

If the 4 numbers are A, B, C, and D, then

take the maximum of (A, B) and call it Max(ab);
take the minimum of (A, B) and call it Min(ab);
take the maximum of (C, D) and call it Max(cd);
take the minimum of (C, D) and call it Min(cd);

Now
the maximum of ( Max(ab), Max(cd) ) is the highest number of the four;
the minimum of ( Min(ab), Min(cd) ) is the lowest number of the four;
the two numbers left (minimum of Max(ab) and maximum of Min(cd))
are the 2nd and 3rd highest, in some order.

Topic archived. No new replies allowed.