On Fri, Nov 30, 2007 at 10:07:19AM -0800, chun ping wang wrote:
hey i am curious on the actual code you written. Cause i want to know if doing that is faster than copying an item to a container and like iterate over that.
I'm sure there are cases when the extra copy performs better than the extra function call per element, but it'll have to be a lot of them to measure the difference. Aas an idiom however I think it's best to avoid copying if possible: for some values it may be rather expensive.
template < class T, class U, template
class CONT > CONT<T> getKeys(const boost::unordered_map & data) { CONT<T> retCont; typedef typename boost::unordered_map ::value_type value_type; BOOST_FOREACH(value_type val, data) { retCont.push_back(val.first); } return retCont; }
Modulo RVO this even copies the data twice. While we're talking iterators why not accept an output iterator as an argument, write to it and return the resulting iterator at the end (cf. std::copy)? This is more generic (the concept of an iterator is simpler and in this case closer to what you really need than the concept of a container) and more flexible, especially with the Boost iterator adapters (e.g. using the previously mentioned transform_iterator you get some kind of for_each). N.