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?

Recommended Answers

All 7 Replies

I would try something like:

int highest = array[0];
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

Member Avatar for iamthwee

What has this got to do with overloading operators?

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

Member Avatar for iamthwee

No I'm asking you what has this

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

got to do with overloading operators? Unless of course, you've been asked by a teacher or someone to explicity do that by overloading an operator?

No I'm asking you what has this

got to do with overloading operators? Unless of course, you've been asked by a teacher or someone to explicity do that by overloading an operator?

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

};
Member Avatar for iamthwee

Ok that makes some sense now.

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

If you're looking for a example, regarding overloading the [] operator try searching for "overloading [] operator c++ matrix".

Since in most cases people overload the [] operator when designing a matrix class.

commented: good +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.