• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_CORE_LIB_GTL_PRIORITY_QUEUE_UTIL_H_
17 #define TENSORFLOW_CORE_LIB_GTL_PRIORITY_QUEUE_UTIL_H_
18 
19 #include <algorithm>
20 #include <queue>
21 #include <utility>
22 
23 namespace tensorflow {
24 namespace gtl {
25 
26 // Removes the top element from a std::priority_queue and returns it.
27 // Supports movable types.
28 template <typename T, typename Container, typename Comparator>
ConsumeTop(std::priority_queue<T,Container,Comparator> * q)29 T ConsumeTop(std::priority_queue<T, Container, Comparator>* q) {
30   // std::priority_queue is required to implement pop() as if it
31   // called:
32   //   std::pop_heap()
33   //   c.pop_back()
34   // unfortunately, it does not provide access to the removed element.
35   // If the element is move only (such as a unique_ptr), there is no way to
36   // reclaim it in the standard API.  std::priority_queue does, however, expose
37   // the underlying container as a protected member, so we use that access
38   // to extract the desired element between those two calls.
39   using Q = std::priority_queue<T, Container, Comparator>;
40   struct Expose : Q {
41     using Q::c;
42     using Q::comp;
43   };
44   auto& c = q->*&Expose::c;
45   auto& comp = q->*&Expose::comp;
46   std::pop_heap(c.begin(), c.end(), comp);
47   auto r = std::move(c.back());
48   c.pop_back();
49   return r;
50 }
51 
52 }  // namespace gtl
53 }  // namespace tensorflow
54 
55 #endif  // TENSORFLOW_CORE_LIB_GTL_PRIORITY_QUEUE_UTIL_H_
56