If I were to overload the subscript operator, aka '[]', it would probably look something like this:

``int &operator[](int);``

If I filled this array with 10 digits.. 1.2.3.4, etc... How could I return the largest digit, and then the next largest digit? etc... I'm not sure if a max function would work, because it would always find the biggest number in the set... and max - 1 could work, but only since my numbers are chronological. Say I had an array of ten random numbers from 1 to 100. Then what would I do?

I would try something like:

``````int highest = array;
for(int a = 0; a < 10; ++a)
{
if(array[a] > highest){highest = array[a];}
}``````

Just take the first element and store it as highest, then walk through the array and if the current element is higher then …

Say I had an array of ten random numbers from 1 to 100. Then what would I do?

You'd sort the numbers in descending order and pick the last two. Order is cool, it makes everything easier. :) Without order you can either write a kludgy brute force algorithm, or …

## All 7 Replies

I would try something like:

``````int highest = array;
for(int a = 0; a < 10; ++a)
{
if(array[a] > highest){highest = array[a];}
}``````

Just take the first element and store it as highest, then walk through the array and if the current element is higher then the variable highest store that value in highest.

Edit: Just read your post clearly, sorry. Thought you were looking for only the highest

Say I had an array of ten random numbers from 1 to 100. Then what would I do?

You'd sort the numbers in descending order and pick the last two. Order is cool, it makes everything easier. :) Without order you can either write a kludgy brute force algorithm, or an insanely complicated efficient algorithm. Order is better 'cause it saves you the hassle of bad or complex code. :D

i don't see that their response has anything to do with overloading operators

No I'm asking you what has this

How could I return the largest digit, and then the next largest digit?

No I'm asking you what has this

Yes, it has been explicity stated that I must overload this operator so... definitionally, the operator must be a member function, because [] is being used.

Maybe it would look like this?

``````class Collection
{
private:
blah;
public:
const int &operator[] (int) const;   //subscript operator

};``````

Ok that makes some sense now.

So in order to find the two largest element you follow Inanna's suggestion.