第一步:使其适用于 C 风格的数组。
第二步:使用基于范围的 for 循环。更少的问题/努力。
第三步:使用模板别名使它更好一点。
#include <iostream>
#include <map>
#include <deque>
#include <cstdint>
#include <functional>
#include <algorithm>
#include <iterator>
template < typename Elem, typename Res >
using return_type = std::multimap < typename std::remove_reference<Elem>::type,
Res>;
template<typename Cont, typename F >
auto group_by (Cont const& c, F const& f)
-> return_type < decltype(*std::begin(c)), decltype(f(*std::begin(c))) >
{
return_type< decltype(*std::begin(c)),
decltype(f(*std::begin(c))) > result;
for(auto const& e : c)
{
auto const& key = f(e);
result.insert( std::make_pair(key,e) );
// alternatively, just:
// result.emplace( f(e), e );
}
return result;
}
int main()
{
char const foo[] = "hello world";
auto result = group_by(foo, [] (uint64_t x){return x%10;});
}
Visual-Studio 支持的版本:
template < typename Cont, typename F >
auto group_by (Cont const& c, F const& f)
-> std::multimap
<
typename std::remove_reference<decltype(*std::begin(c))>::type,
decltype(f(*std::begin(c)))
>
{
using key_ref = decltype( *std::begin(c) );
using key_type = typename std::remove_reference < key_ref > :: type;
using value_type = decltype( f(*std::begin(c)) );
std::multimap < key_type, value_type > result;
for(auto const& e : c)
{
result.emplace( f(e), e );
}
return result;
}
第四步:使用迭代器而不是传递容器。
#include <iostream>
#include <map>
#include <deque>
#include <cstdint>
#include <functional>
#include <algorithm>
#include <iterator>
template < typename Elem, typename Res >
using return_type = std::multimap< typename std::remove_reference<Elem>::type,
Res >;
template < typename FwdIt, typename F >
auto group_by (FwdIt beg, FwdIt end, F const& f)
-> return_type < decltype(*beg), decltype(f(*beg)) >
{
return_type < decltype(*beg), decltype(f(*beg)) > result;
for(FwdIt i = beg; i != end; ++i)
{
result.emplace( f(*i), *i );
}
return result;
}
int main()
{
char const foo[] = "hello world";
auto result = group_by( std::begin(foo), std::end(foo),
[] (uint64_t x){return x%10;} );
}
Visual-Studio 支持的版本:
template < typename FwdIt, typename F >
auto group_by (FwdIt beg, FwdIt end, F const& f)
-> std::multimap
<
typename std::remove_reference<decltype(*std::begin(c))>::type,
decltype(f(*std::begin(c)))
>
{
using key_ref = decltype( *std::begin(c) );
using key_type = typename std::remove_reference < key_ref > :: type;
using value_type = decltype( f(*std::begin(c)) );
std::multimap < key_type, value_type > result;
for(FwdIt i = beg; i != end; ++i)
{
result.emplace( f(*i), *i );
}
return result;
}