max_m_elements.hxx
Go to the documentation of this file.
1 /*===========================================================================================================
2  *
3  * SHA - Simple Hybesis Algorithms
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/michael-jeulinl/Simple-Hybesis-Algorithms/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 SHA_Search
28 {
50  template <typename Container,
51  typename IT,
52  typename Compare = std::greater_equal<typename std::iterator_traits<IT>::value_type>>
53  Container MaxMElements(const IT& begin, const IT& end, const int m)
54  {
55  if (m < 1 || m > std::distance(begin, end))
56  return Container();
57 
58  // Initiale values depends on the comparator functor
59  const auto limitValue = Compare()(0, std::numeric_limits<typename std::iterator_traits<IT>::value_type>::
60  lowest()) ?
61  std::numeric_limits<typename std::iterator_traits<IT>::value_type>::
62  lowest() :
63  std::numeric_limits<typename std::iterator_traits<IT>::value_type>::
64  max();
65 
66  // Allocate the container final size
67  Container maxMElements;
68  maxMElements.resize(m, limitValue);
69  for (auto it = begin; it != end; ++it)
70  {
71  // Insert the value at the right place and bubble down replacement value
72  int index = 0;
73  auto tmpVal = *it;
74  for (auto subIt = maxMElements.begin(); index < m; ++subIt, ++index)
75  if (Compare()(tmpVal, *subIt))
76  std::swap(*subIt, tmpVal);
77  }
78 
79  return maxMElements;
80  }
81 }
82 
83 #endif // MODULE_COLLECTIONS_SEARCH_HXX
Container MaxMElements(const IT &begin, const IT &end, const int m)