max_m_elements.hxx
Go to the documentation of this file.
1 /*===========================================================================================================
2  *
3  * HUC - Hurna Core
4  *
5  * Copyright (c) Michael Jeulin-Lagarrigue
6  *
7  * Licensed under the MIT License, you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * https://github.com/Hurna/Hurna-Core/blob/master/LICENSE
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License is
13  * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and limitations under the License.
15  *
16  * The above copyright notice and this permission notice shall be included in all copies or
17  * substantial portions of the Software.
18  *
19  *=========================================================================================================*/
20 #ifndef MODULE_SEARCH_MAX_M_ELEMENTS_HXX
21 #define MODULE_SEARCH_MAX_M_ELEMENTS_HXX
22 
23 // STD includes
24 #include <functional>
25 #include <limits>
26 
27 namespace huc
28 {
29  namespace search
30  {
48  template <typename Container,
49  typename IT,
50  typename Compare = std::greater_equal<typename std::iterator_traits<IT>::value_type>>
51  Container MaxMElements(const IT& begin, const IT& end, const int m)
52  {
53  if (m < 1 || m > std::distance(begin, end))
54  return Container();
55 
56  // Initiale values depends on the comparator functor
57  const auto limitValue = Compare()(0,
58  std::numeric_limits<typename std::iterator_traits<IT>::value_type>::lowest()) ?
59  std::numeric_limits<typename std::iterator_traits<IT>::value_type>::lowest() :
60  std::numeric_limits<typename std::iterator_traits<IT>::value_type>::max();
61 
62  // Allocate the container final size
63  Container maxMElements;
64  maxMElements.resize(m, limitValue);
65  for (auto it = begin; it != end; ++it)
66  {
67  // Insert the value at the right place and bubble down replacement value
68  int index = 0;
69  auto tmpVal = *it;
70  for (auto subIt = maxMElements.begin(); index < m; ++subIt, ++index)
71  if (Compare()(tmpVal, *subIt))
72  std::swap(*subIt, tmpVal);
73  }
74 
75  return maxMElements;
76  }
77  }
78 }
79 
80 #endif // MODULE_COLLECTIONS_SEARCH_HXX
Container MaxMElements(const IT &begin, const IT &end, const int m)