snark
voted_tracking.h
1 // This file is part of snark, a generic and flexible library
2 // for robotics research.
3 //
4 // Copyright (C) 2011 The University of Sydney
5 //
6 // snark is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 3 of the License, or (at your option) any later version.
10 //
11 // snark is distributed in the hope that it will be useful, but WITHOUT ANY
12 // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
14 // for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with snark. If not, see <http://www.gnu.org/licenses/>.
18 
19 #ifndef SNARK_PERCEPTION_ALGORITHMS_ALGORITHMS_VOTEDTRACKING_HEADER_GUARD_
20 #define SNARK_PERCEPTION_ALGORITHMS_ALGORITHMS_VOTEDTRACKING_HEADER_GUARD_
21 
22 #include <stdlib.h>
23 #include <algorithm>
24 #include <map>
25 #include <boost/optional.hpp>
26 
27 namespace snark {
28 
48 template < typename It, typename Id, typename F >
49 Id voted_tracking( It begin, It end, F GetPreviousId, Id vacantId );
50 
51 namespace impl {
52 
53 template < typename P > inline bool comparePairs( const P& i, const P& j ) { return i.second < j.second; }
54 
55 } // namespace impl {
56 
57 template < typename It, typename Id, typename F >
58 inline Id voted_tracking( It begin, It end, F getPreviousId, Id vacantId )
59 {
60  typedef std::map< Id, std::size_t > Map;
61  typedef std::pair< Id, std::size_t > Pair;
62  Map ids;
63  for( It it = begin; it != end; ++it )
64  {
65  boost::optional< Id > previous = getPreviousId( it );
66  if( !previous ) { continue; }
67  std::pair< typename Map::iterator, bool > p = ids.insert( Pair( *previous, 0 ) );
68  if( !p.second ) { ++p.first->second; }
69  }
70  return ids.empty() ? vacantId
71  : std::max_element( ids.begin(), ids.end(), impl::comparePairs< Pair > )->first;
72 }
73 
74 } // namespace snark {
75 
76 #endif // #ifndef SNARK_PERCEPTION_ALGORITHMS_ALGORITHMS_VOTEDTRACKING_HEADER_GUARD_