简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM