Problem
I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest.
Preferably this should be solved with the STL. boost::* or stl::tr1::* (from VS9 with Featurepack) are also possible.
Example of timestamped data:
struct STimestampedData
{
time_t m_timestamp; // Sorting criterion
CData m_data; // Payload
}
Approach with stl::vector
, sort()
and equal_range()
Since a map
or set
only allows me to find exact matches, I don't get any further using one of these.
So now I have a vector
to which I append data as it is coming in. Before searching I use <algorithm>
's sort()
and supply it with a custom comparison function.
After that I use <algorithm>
's equal_range()
to find the two neighbors of a specified value x
.
From these two values I check which one is closest to x
and then I have my best match.
While this is not too complex, I wonder if there are more elegant solutions to this.
Maybe the STL already has an algorithm which does exactly that so I'm not re-inventing something here?
Update: Linear vs. binary search
I forgot to mention that I have quite a lot of data to handle so I don't want to have to search linearly.
The reason I am sorting a vector with sort()
is because it has random access iterators which is not the case with a map
. Using a map
would not allow equal_range()
to do a search with twice logarithmic complexity.
Am I correct?