Scoped / Reference Counted Iterator
I'm looking for a way to simulated a "scoped iterator" (for lack of a better phrase). Basically, I want to get an iterator from a collection (map in this case) and wrap it in a "scoped iterator" that would remove the element/iterator from the collection once the last reference was dropped. My current approach is below, but I'm looking for something more elegant.
typedef std::map<int,bool> map_type;
typedef map_type::iterator iter_type;
void iterDelete( std::shared_ptr<map_type> map, iter_type * iter)
{
map->erase(*iter);
delete(iter);
}
int main()
{
std开发者_高级运维::shared_ptr<map_type> myMap( new map_type() ); //std::map because iterators are not invalidated by erase/insert
iter_type myIter = myMap->find(7);
std::shared_ptr<iter_type> scopedIter( new iter_type(myIter), std::bind(iterDelete, myMap, std::placeholders::_1) ); //Deleters keep map in scope until all "scoped iterators" die.
}
The easiest thing to do would be to just use a custom deleter for shared_ptr that will remove the element from the map. Also, void main() is Bad.
精彩评论