Hello there, I have to overload the subscript operator to return the largest element of a collection, the second largest, the third largest, and so on.
I don't really understand what to do. Do I have to create an array and sort it? What the output will looks like? I'm confused.Nicole

Not sure if you are doing templates or not, but templates provide the most reusable solution... Here is a simple solution using templates and will work on any collection having any type of data. This could be adapted to be a member method of the collection class. If you move this to the collection class, then the index that is being built in the method could be maintained by the collection and all this method would need to do is access the index to find the apropariate item:

// C is the collection type and I is the item type.
template<class C, class I>
I& operator[](C& someCollection, long index)
{
   // must build an index (sorted list) of the items in the collection
   // would be better if this index could be built and maintained by the
   // collection, and then this index operator could be embeded in the 
   // collection class....
   vector<Iterator> index = new vector<Iterator>[someCollection.size()];
   Iterator cIter;
   for(cIter = someCollection.begin(); cIter != someCollection.end(); cIter++)
   {
        Iterator vIter;
        for (vIter=0;vIter!=index.end();vIter++)
        {
              if (*(index[i]) > *iter)
                      break; // found a place to insert the item into the index
        }
        index.insert(vIter, iter);
   }

   return *(index[index]);
}

I fixed a couple of problems I noticed after I submitted the posting....

// C is the collection type and I is the item type.
template<class I, class C<I>>
I& operator[](C<I>& someCollection, long index)
{
// must build an index (sorted list) of the items in the collection
// would be better if this index could be built and maintained by the
// collection, and then this index operator could be embeded in the
// collection class....
vector<Iterator>& index = *(new vector<Iterator>[someCollection.size()]);
Iterator cIter;
for(cIter = someCollection.begin(); cIter != someCollection.end(); cIter++)
{
Iterator vIter;
for (vIter=0;vIter!=index.end();vIter++)
{
if (*(index) > *iter)
break; // found a place to insert the item into the index
}
index.insert(vIter, iter);
}

I& retVal= *(index[index]);
delete index;
return retVal;
}

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.