我的地图定义如下:
map<string, LocationStruct> myLocations;
其中键是时间字符串
我只在此地图中保留了40个项目,并且当我达到40个项目时,我想放弃地图中的最后一个项目.我知道我做不到myLocations.erase(myLocations.end())
,所以我该怎么做呢?
我打算让地图中的最后一项成为最早的项目,因此也是FIFO.数据会很快(大约20Hz)进来,所以我希望地图可以跟上它.我确实需要根据时间查找数据,所以我确实需要它作为关键,但我愿意采用其他方法来实现这一点.
字符串的格式是一个非常详细的"星期六6月21日星期四18:44:21:281",虽然我可以把它简化为简单时代以来的秒数.这是我的第一次尝试,并没有过多考虑格式.
Jam*_*nze 12
最惯用的方式是:
myLocations.erase( std::prev( myLocations.end() ) );
Run Code Online (Sandbox Code Playgroud)
如果您没有C++ 11,请使用工具箱中的相应功能.
我假设当你说"擦除最后一个元素"时,你的意思是"擦除最旧元素".
我不会多次使用字符串,而是使用日期/时间类型(如unix时间戳).然后他们myLocations.erase(myLocations.begin())
将按时间排序,而不是按字典顺序排序,你可以,因为最老的人总是在开头.
更好的是,使用a ,并用它来按时间查找元素.这将自动删除最旧的,并且在按时间查找元素时具有相同的对数复杂度.添加数据时速度也更快.对于你的情况来说,它几乎全赢.如果你真的想避免,那么最适合你的需求,并提供出色的表现,但如果你已经有了工作,那么坚持下去可能是最好的.boost::circular_buffer
<std::pair<timetype, LocationStruct>>
std::lower_bound
boost
std::deque
map
std::map
以下是如何进行查找deque
:
typedef ???? timetype;
typedef std::pair<Timetype, LocationStruct> TimeLocPair
typedef std::deque<TimeLocPair> LocationContainer;
typedef LocationContainer::const_iterator LocationIterator;
bool compareTimeLocPair(const TimeLocPair& lhs, const TimeLocPair& rhs)
{return lhs.first < rhs.first;}
LocationIterator find(const LocationContainer& cont, timetype time) {
TimeLocPair finder(time, LocationStruct());
LocationIterator it = std::lower_bound(cont.begin(), cont.end(), finder, compareTimeLocPair);
if (it == cont.end() || it->first != time)
return cont.end();
return it;
}
Run Code Online (Sandbox Code Playgroud)
试试这个,它有效:
map<string, LocationStruct>::iterator it = myLocations.end();
it--;
myLocations.erase(it);
Run Code Online (Sandbox Code Playgroud)