OR-Tools  9.6
sorted.h
Go to the documentation of this file.
1 // Copyright 2010-2022 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifndef OR_TOOLS_MATH_OPT_STORAGE_SORTED_H_
15 #define OR_TOOLS_MATH_OPT_STORAGE_SORTED_H_
16 
17 #include <algorithm>
18 #include <vector>
19 
20 #include "absl/algorithm/container.h"
21 #include "absl/container/flat_hash_map.h"
22 #include "absl/container/flat_hash_set.h"
23 #include "google/protobuf/map.h"
24 
26 
27 template <typename T>
28 std::vector<T> SortedElements(const absl::flat_hash_set<T>& elements) {
29  std::vector<T> result(elements.begin(), elements.end());
30  absl::c_sort(result);
31  return result;
32 }
33 
34 template <typename K, typename V>
35 std::vector<K> MapKeys(const absl::flat_hash_map<K, V>& in_map) {
36  std::vector<K> keys;
37  keys.reserve(in_map.size());
38  for (const auto& key_pair : in_map) {
39  keys.push_back(key_pair.first);
40  }
41  return keys;
42 }
43 
44 template <typename K, typename V>
45 std::vector<K> MapKeys(const google::protobuf::Map<K, V>& in_map) {
46  std::vector<K> keys;
47  keys.reserve(in_map.size());
48  for (const auto& key_pair : in_map) {
49  keys.push_back(key_pair.first);
50  }
51  return keys;
52 }
53 
54 template <typename K, typename V>
55 std::vector<K> SortedMapKeys(const absl::flat_hash_map<K, V>& in_map) {
56  std::vector<K> keys = MapKeys(in_map);
57  std::sort(keys.begin(), keys.end());
58  return keys;
59 }
60 
61 template <typename K, typename V>
62 std::vector<K> SortedMapKeys(const google::protobuf::Map<K, V>& in_map) {
63  std::vector<K> keys = MapKeys(in_map);
64  std::sort(keys.begin(), keys.end());
65  return keys;
66 }
67 
68 } // namespace operations_research::math_opt
69 
70 #endif // OR_TOOLS_MATH_OPT_STORAGE_SORTED_H_
std::vector< K > MapKeys(const absl::flat_hash_map< K, V > &in_map)
Definition: sorted.h:35
std::vector< K > SortedMapKeys(const absl::flat_hash_map< K, V > &in_map)
Definition: sorted.h:55
std::vector< T > SortedElements(const absl::flat_hash_set< T > &elements)
Definition: sorted.h:28