Przemek wrote:
what is the efficient way to find all distinct keys in a multimap.
Use a version of the standard library 'unique()' algorithm:
/**/ template <typename T1, typename T2>
/**/ struct pred {
/**/ typedef typename std::multimap<T1, T2>::value_type value_type;
/**/ bool
/**/ operator()(value_type const& v1, value_type const& v2) const {
/**/ return v1.first == v2.first;
/**/ }
/**/ };
/**/
/**/ template <typename T1, typename T2>
/**/ std::vector<T1>
/**/ get_distinct_keys(std::multimap<T1, T2> const& nMap)
/**/ {
/**/ std::vector<T1> distinct;
/**/ std::unique_copy(nMap.begin(), nMap.end(),
/**/ std::back_inserter(distinct),
/**/ pred<T1, T2>());
/**/ return distinct;
/**/ }
After writing this code, I realized that this does not really
do the trick: this tries to assign a pair to a value. It would
be necessary to use an iterator projecting the 'first' component
of the 'std::multimap's 'pair'. I think Boost
(<http://www.boost.org/>) has such iterators. Alternatively,
you could use 'std::transform()' to do the projection first and
then eliminate duplicate keys using 'std::reserve()' on the
container prior to returning it. However, this assumes that the
number of keys removed is relatively small compared to the
total number of keys. Otherwise, the projection approach is
probably preferable.
BTW, THE approach to returning sequences is not by returning
some sequence but rather to accept an output iterator as
argument.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting