c++ - When implementing Trees/Heaps/Lists etc, why should a `find` method return an iterator to the object instead of the obect itself? -


i see lot of different c++ programmers more knowledgeable myself time in data structure implementations. example in this avl tree implementation,

/** * iterator find(const key& key); * const_iterator find(const key& key); * usage: if (myavltree.find("skiplist") != myavltree.end()) { ... } * ------------------------------------------------------------------------- * returns iterator entry in avl tree specified key, * or end() as sentinel if not exist. */ iterator find(const key& key); const_iterator find(const key& key) const; 

i'm trying figure out in situation more useful returning value corresponds key.

if adopt own implementations (assuming designing sort of container) when benefit me so?

returning iterator has several significant advantages:

(1) it's strategy indicating failure if key not found; namely, returning end() indicates key not found. alternatives include throwing exception, (which at() member function do), or returning nullptr, require pointer also returned on success.

(2) data structures maintain order, such std::map. when iterator returned, enables caller increment or decrement iterator next/previous key/value pair in ordering.

(3) many standard container member functions take iterator parameter, such std::vector::erase or std::map::erase. passing in iterator, container may able efficiently operate on specific elements, without having lookup key. example, std::map::erase(const key_type&) o(log(n)) operation, std::map::erase(iterator) o(1) operation.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -