libstdc++
stl_stack.h
Go to the documentation of this file.
1// Stack implementation -*- C++ -*-
2
3// Copyright (C) 2001-2026 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/*
26 *
27 * Copyright (c) 1994
28 * Hewlett-Packard Company
29 *
30 * Permission to use, copy, modify, distribute and sell this software
31 * and its documentation for any purpose is hereby granted without fee,
32 * provided that the above copyright notice appear in all copies and
33 * that both that copyright notice and this permission notice appear
34 * in supporting documentation. Hewlett-Packard Company makes no
35 * representations about the suitability of this software for any
36 * purpose. It is provided "as is" without express or implied warranty.
37 *
38 *
39 * Copyright (c) 1996,1997
40 * Silicon Graphics Computer Systems, Inc.
41 *
42 * Permission to use, copy, modify, distribute and sell this software
43 * and its documentation for any purpose is hereby granted without fee,
44 * provided that the above copyright notice appear in all copies and
45 * that both that copyright notice and this permission notice appear
46 * in supporting documentation. Silicon Graphics makes no
47 * representations about the suitability of this software for any
48 * purpose. It is provided "as is" without express or implied warranty.
49 */
50
51/** @file bits/stl_stack.h
52 * This is an internal header file, included by other library headers.
53 * Do not attempt to use it directly. @headername{stack}
54 */
55
56#ifndef _STL_STACK_H
57#define _STL_STACK_H 1
58
59#include <bits/concept_check.h>
60#include <debug/debug.h>
61#if __cplusplus >= 201103L
62# include <bits/uses_allocator.h>
63#endif
64#if __glibcxx_containers_ranges // C++ >= 23
65# include <ranges> // ranges::to
66# include <bits/ranges_algobase.h> // ranges::copy
67#endif
68
69namespace std _GLIBCXX_VISIBILITY(default)
70{
71_GLIBCXX_BEGIN_NAMESPACE_VERSION
72
73#if __glibcxx_format_ranges
74 template<typename, typename> class formatter;
75#endif
76
77 /**
78 * @brief A standard container giving FILO behavior.
79 *
80 * @ingroup sequences
81 *
82 * @tparam _Tp Type of element.
83 * @tparam _Sequence Type of underlying sequence, defaults to deque<_Tp>.
84 *
85 * Meets many of the requirements of a
86 * <a href="tables.html#65">container</a>,
87 * but does not define anything to do with iterators. Very few of the
88 * other standard container interfaces are defined.
89 *
90 * This is not a true container, but an @e adaptor. It holds
91 * another container, and provides a wrapper interface to that
92 * container. The wrapper is what enforces strict
93 * first-in-last-out %stack behavior.
94 *
95 * The second template parameter defines the type of the underlying
96 * sequence/container. It defaults to std::deque, but it can be
97 * any type that supports @c back, @c push_back, and @c pop_back,
98 * such as std::list, std::vector, or an appropriate user-defined
99 * type.
100 *
101 * Members not found in @a normal containers are @c container_type,
102 * which is a typedef for the second Sequence parameter, and @c
103 * push, @c pop, and @c top, which are standard %stack/FILO
104 * operations.
105 */
106 template<typename _Tp, typename _Sequence = deque<_Tp> >
107 class stack
108 {
109#ifdef _GLIBCXX_CONCEPT_CHECKS
110 // concept requirements
111 typedef typename _Sequence::value_type _Sequence_value_type;
112# if __cplusplus < 201103L
113 __glibcxx_class_requires(_Tp, _SGIAssignableConcept)
114 __glibcxx_class_requires(_Sequence, _BackInsertionSequenceConcept)
115# endif
116 __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept)
117#endif
118
119 template<typename _Tp1, typename _Seq1>
120 friend _GLIBCXX26_CONSTEXPR bool
121 operator==(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
122
123 template<typename _Tp1, typename _Seq1>
124 friend _GLIBCXX26_CONSTEXPR bool
125 operator<(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
126
127#if __cpp_lib_three_way_comparison
128 template<typename _Tp1, three_way_comparable _Seq1>
129 friend _GLIBCXX26_CONSTEXPR compare_three_way_result_t<_Seq1>
130 operator<=>(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
131#endif
132
133#if __cplusplus >= 201103L
134 template<typename _Alloc>
135 using _Uses = typename
137
138#if __cplusplus >= 201703L
139 // _GLIBCXX_RESOLVE_LIB_DEFECTS
140 // 2566. Requirements on the first template parameter of container
141 // adaptors
143 "value_type must be the same as the underlying container");
144#endif // C++17
145#endif // C++11
146
147 public:
148 typedef typename _Sequence::value_type value_type;
149 typedef typename _Sequence::reference reference;
150 typedef typename _Sequence::const_reference const_reference;
151 typedef typename _Sequence::size_type size_type;
152 typedef _Sequence container_type;
153
154 protected:
155 // See queue::c for notes on this name.
156 _Sequence c;
157
158 public:
159 // XXX removed old def ctor, added def arg to this one to match 14882
160 /**
161 * @brief Default constructor creates no elements.
162 */
163#if __cplusplus < 201103L
164 explicit
165 stack(const _Sequence& __c = _Sequence())
166 : c(__c) { }
167#else
168 template<typename _Seq = _Sequence, typename _Requires = typename
170 _GLIBCXX26_CONSTEXPR
172 : c() { }
173
174 explicit _GLIBCXX26_CONSTEXPR
175 stack(const _Sequence& __c)
176 : c(__c) { }
177
178 explicit _GLIBCXX26_CONSTEXPR
179 stack(_Sequence&& __c)
180 : c(std::move(__c)) { }
181
182#ifdef __glibcxx_adaptor_iterator_pair_constructor // C++ >= 23 && HOSTED
183 template<typename _InputIterator,
184 typename = _RequireInputIter<_InputIterator>>
185 _GLIBCXX26_CONSTEXPR
186 stack(_InputIterator __first, _InputIterator __last)
187 : c(__first, __last) { }
188#endif
189
190#if __glibcxx_containers_ranges // C++ >= 23
191 /**
192 * @brief Construct a stack from a range.
193 * @since C++23
194 */
195 template<__detail::__container_compatible_range<_Tp> _Rg>
196 _GLIBCXX26_CONSTEXPR
197 stack(from_range_t, _Rg&& __rg)
198 : c(ranges::to<_Sequence>(std::forward<_Rg>(__rg)))
199 { }
200
201 /**
202 * @brief Construct a stack from a range.
203 * @since C++23
204 */
205 template<__detail::__container_compatible_range<_Tp> _Rg,
206 typename _Alloc>
207 _GLIBCXX26_CONSTEXPR
208 stack(from_range_t, _Rg&& __rg, const _Alloc& __a)
209 : c(ranges::to<_Sequence>(std::forward<_Rg>(__rg), __a))
210 { }
211#endif
212
213 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
214 explicit _GLIBCXX26_CONSTEXPR
215 stack(const _Alloc& __a)
216 : c(__a) { }
217
218 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
219 _GLIBCXX26_CONSTEXPR
220 stack(const _Sequence& __c, const _Alloc& __a)
221 : c(__c, __a) { }
222
223 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
224 _GLIBCXX26_CONSTEXPR
225 stack(_Sequence&& __c, const _Alloc& __a)
226 : c(std::move(__c), __a) { }
227
228 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
229 _GLIBCXX26_CONSTEXPR
230 stack(const stack& __q, const _Alloc& __a)
231 : c(__q.c, __a) { }
232
233 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
234 _GLIBCXX26_CONSTEXPR
235 stack(stack&& __q, const _Alloc& __a)
236 : c(std::move(__q.c), __a) { }
237
238#if __cplusplus > 202002L
239 template<typename _InputIterator, typename _Alloc,
240 typename = _RequireInputIter<_InputIterator>,
241 typename = _Uses<_Alloc>>
242 _GLIBCXX26_CONSTEXPR
243 stack(_InputIterator __first, _InputIterator __last, const _Alloc& __a)
244 : c(__first, __last, __a) { }
245#endif
246#endif
247
248 /**
249 * Returns true if the %stack is empty.
250 */
251 _GLIBCXX_NODISCARD
252 _GLIBCXX26_CONSTEXPR bool
253 empty() const
254 { return c.empty(); }
255
256 /** Returns the number of elements in the %stack. */
257 _GLIBCXX_NODISCARD
258 _GLIBCXX26_CONSTEXPR size_type
259 size() const
260 { return c.size(); }
261
262 /**
263 * Returns a read/write reference to the data at the first
264 * element of the %stack.
265 */
266 _GLIBCXX_NODISCARD
267 _GLIBCXX26_CONSTEXPR reference
269 {
270 __glibcxx_requires_nonempty();
271 return c.back();
272 }
273
274 /**
275 * Returns a read-only (constant) reference to the data at the first
276 * element of the %stack.
277 */
278 _GLIBCXX_NODISCARD
279 _GLIBCXX26_CONSTEXPR const_reference
280 top() const
281 {
282 __glibcxx_requires_nonempty();
283 return c.back();
284 }
285
286 /**
287 * @brief Add data to the top of the %stack.
288 * @param __x Data to be added.
289 *
290 * This is a typical %stack operation. The function creates an
291 * element at the top of the %stack and assigns the given data
292 * to it. The time complexity of the operation depends on the
293 * underlying sequence.
294 */
295 _GLIBCXX26_CONSTEXPR void
296 push(const value_type& __x)
297 { c.push_back(__x); }
298
299#if __cplusplus >= 201103L
300 _GLIBCXX26_CONSTEXPR void
301 push(value_type&& __x)
302 { c.push_back(std::move(__x)); }
303
304#if __cplusplus > 201402L
305 template<typename... _Args>
306 _GLIBCXX26_CONSTEXPR decltype(auto)
307 emplace(_Args&&... __args)
308 { return c.emplace_back(std::forward<_Args>(__args)...); }
309#else
310 template<typename... _Args>
311 void
312 emplace(_Args&&... __args)
313 { c.emplace_back(std::forward<_Args>(__args)...); }
314#endif
315#endif
316
317#if __glibcxx_containers_ranges // C++ >= 23
318 template<__detail::__container_compatible_range<_Tp> _Rg>
319 _GLIBCXX26_CONSTEXPR void
320 push_range(_Rg&& __rg)
321 {
322 if constexpr (requires { c.append_range(std::forward<_Rg>(__rg)); })
323 c.append_range(std::forward<_Rg>(__rg));
324 else
325 ranges::copy(__rg, std::back_inserter(c));
326 }
327#endif
328
329 /**
330 * @brief Removes first element.
331 *
332 * This is a typical %stack operation. It shrinks the %stack
333 * by one. The time complexity of the operation depends on the
334 * underlying sequence.
335 *
336 * Note that no data is returned, and if the first element's
337 * data is needed, it should be retrieved before pop() is
338 * called.
339 */
340 _GLIBCXX26_CONSTEXPR void
342 {
343 __glibcxx_requires_nonempty();
344 c.pop_back();
345 }
346
347#if __cplusplus >= 201103L
348 _GLIBCXX26_CONSTEXPR void
349 swap(stack& __s)
350#if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11
351 noexcept(__is_nothrow_swappable<_Sequence>::value)
352#else
353 noexcept(__is_nothrow_swappable<_Tp>::value)
354#endif
355 {
356 using std::swap;
357 swap(c, __s.c);
358 }
359#endif // __cplusplus >= 201103L
360
361#if __glibcxx_format_ranges
362 friend class formatter<stack<_Tp, _Sequence>, char>;
363 friend class formatter<stack<_Tp, _Sequence>, wchar_t>;
364#endif
365 };
366
367#if __cpp_deduction_guides >= 201606
368 template<typename _Container,
369 typename = _RequireNotAllocator<_Container>>
371
372 template<typename _Container, typename _Allocator,
373 typename = _RequireNotAllocator<_Container>>
374 stack(_Container, _Allocator)
376
377#ifdef __glibcxx_adaptor_iterator_pair_constructor
378 template<typename _InputIterator,
379 typename _ValT
381 typename = _RequireInputIter<_InputIterator>>
382 stack(_InputIterator, _InputIterator) -> stack<_ValT>;
383
384 template<typename _InputIterator, typename _Allocator,
385 typename _ValT
387 typename = _RequireInputIter<_InputIterator>,
388 typename = _RequireAllocator<_Allocator>>
389 stack(_InputIterator, _InputIterator, _Allocator)
391#endif
392
393#if __glibcxx_containers_ranges // C++ >= 23
394 template<ranges::input_range _Rg>
395 stack(from_range_t, _Rg&&) -> stack<ranges::range_value_t<_Rg>>;
396
397 template<ranges::input_range _Rg, __allocator_like _Alloc>
398 stack(from_range_t, _Rg&&, _Alloc)
401#endif
402#endif
403
404 /**
405 * @brief Stack equality comparison.
406 * @param __x A %stack.
407 * @param __y A %stack of the same type as @a __x.
408 * @return True iff the size and elements of the stacks are equal.
409 *
410 * This is an equivalence relation. Complexity and semantics
411 * depend on the underlying sequence type, but the expected rules
412 * are: this relation is linear in the size of the sequences, and
413 * stacks are considered equivalent if their sequences compare
414 * equal.
415 */
416 template<typename _Tp, typename _Seq>
417 _GLIBCXX_NODISCARD
418 inline _GLIBCXX26_CONSTEXPR bool
419 operator==(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
420 { return __x.c == __y.c; }
421
422 /**
423 * @brief Stack ordering relation.
424 * @param __x A %stack.
425 * @param __y A %stack of the same type as @a x.
426 * @return True iff @a x is lexicographically less than @a __y.
427 *
428 * This is an total ordering relation. Complexity and semantics
429 * depend on the underlying sequence type, but the expected rules
430 * are: this relation is linear in the size of the sequences, the
431 * elements must be comparable with @c <, and
432 * std::lexicographical_compare() is usually used to make the
433 * determination.
434 */
435 template<typename _Tp, typename _Seq>
436 _GLIBCXX_NODISCARD
437 inline _GLIBCXX26_CONSTEXPR bool
438 operator<(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
439 { return __x.c < __y.c; }
440
441 /// Based on operator==
442 template<typename _Tp, typename _Seq>
443 _GLIBCXX_NODISCARD
444 inline _GLIBCXX26_CONSTEXPR bool
445 operator!=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
446 { return !(__x == __y); }
447
448 /// Based on operator<
449 template<typename _Tp, typename _Seq>
450 _GLIBCXX_NODISCARD
451 inline _GLIBCXX26_CONSTEXPR bool
452 operator>(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
453 { return __y < __x; }
454
455 /// Based on operator<
456 template<typename _Tp, typename _Seq>
457 _GLIBCXX_NODISCARD
458 inline _GLIBCXX26_CONSTEXPR bool
459 operator<=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
460 { return !(__y < __x); }
461
462 /// Based on operator<
463 template<typename _Tp, typename _Seq>
464 _GLIBCXX_NODISCARD
465 inline _GLIBCXX26_CONSTEXPR bool
466 operator>=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
467 { return !(__x < __y); }
468
469#if __cpp_lib_three_way_comparison
470 template<typename _Tp, three_way_comparable _Seq>
471 [[nodiscard]]
472 inline _GLIBCXX26_CONSTEXPR compare_three_way_result_t<_Seq>
473 operator<=>(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
474 { return __x.c <=> __y.c; }
475#endif
476
477#if __cplusplus >= 201103L
478 template<typename _Tp, typename _Seq>
479 inline _GLIBCXX26_CONSTEXPR
480#if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11
481 // Constrained free swap overload, see p0185r1
483#else
484 void
485#endif
486 swap(stack<_Tp, _Seq>& __x, stack<_Tp, _Seq>& __y)
487 noexcept(noexcept(__x.swap(__y)))
488 { __x.swap(__y); }
489
490 template<typename _Tp, typename _Seq, typename _Alloc>
491 struct uses_allocator<stack<_Tp, _Seq>, _Alloc>
492 : public uses_allocator<_Seq, _Alloc>::type { };
493#endif // __cplusplus >= 201103L
494
495_GLIBCXX_END_NAMESPACE_VERSION
496} // namespace
497
498#endif /* _STL_STACK_H */
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:138
constexpr _Tp && forward(typename std::remove_reference< _Tp >::type &__t) noexcept
Forward an lvalue.
Definition move.h:72
constexpr back_insert_iterator< _Container > back_inserter(_Container &__x)
ISO C++ entities toplevel namespace is std.
typename __detail::__cmp3way_res_impl< _Tp, _Up >::type compare_three_way_result_t
[cmp.result], result of three-way comparison
Definition compare:547
Define a member typedef type only if a boolean constant is true.
Definition type_traits:137
Declare uses_allocator so it can be specialized in <queue> etc.
Definition memoryfwd.h:76
A standard container using fixed-size memory allocation and constant-time manipulation of elements at...
Definition stl_deque.h:854
A standard container giving FILO behavior.
Definition stl_stack.h:108
constexpr const_reference top() const
Definition stl_stack.h:280
constexpr bool empty() const
Definition stl_stack.h:253
constexpr stack()
Default constructor creates no elements.
Definition stl_stack.h:171
constexpr size_type size() const
Definition stl_stack.h:259
constexpr void pop()
Removes first element.
Definition stl_stack.h:341
constexpr void push(const value_type &__x)
Add data to the top of the stack.
Definition stl_stack.h:296
constexpr reference top()
Definition stl_stack.h:268