Boost logo

Boost Users :

From: Niels Aan de Brugh (nielsadb_at_[hidden])
Date: 2007-12-03 16:27:19


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 <typename ELEM, typename = std::allocator<ELEM> >
> class CONT
> >
> CONT<T> getKeys(const boost::unordered_map<T, U>& data)
> {
> CONT<T> retCont;
> typedef typename boost::unordered_map<T, U>::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.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net