Sorting a vector of Indeces

Lets say I have a huge vector of objects called Log. A log contains a timestamp, a category and message. This vector cannot be changed.

Searches are to be performed on the above vector and the results are to be stored. To minimize memory and increase effeciency, the search results are stored in another vector. This vector contains the indices of the search results from first vector. If I were to sort the vector of indices, how would I go about doing that using the stl? The sort has to be ascending by timestamp with ties broken by category and further ties broken by index number.

Create a functor that sorts on the proper criteria.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct SortByTimestamp
{
  const vector <Log> & log;

  SortByTimestamp( const vector <Log> & log ): log( log ) { }

  bool operator () ( index a, index b )
  {
    return log.at( a ) < log.at( b );  // or however your Log type is indexed
  }
};

int main()
{
  vector <Log> mylog;
  ...  // mylog is populated

  vector <index> myilog;
  ...  // myilog is mapped to mylog

  // Sort myilog based upon the indexed values in mylog
  std::sort( std::begin(myilog), std::end(myilog), SortByTimestamp(mylog) );

It might be a good idea to try to encapsulate some of these types into a class. (Technically, a Log is a list of LogEntries. So your "Log" class should be a "LogEntry" and the vector of LogEntries should be the "Log". Etc.)

Hope this helps.
Topic archived. No new replies allowed.