libstdc++
stl_stack.h
Go to the documentation of this file.
1// Stack implementation -*- C++ -*-
2
3// Copyright (C) 2001-2025 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_ranges_to_container // 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 /**
74 * @brief A standard container giving FILO behavior.
75 *
76 * @ingroup sequences
77 *
78 * @tparam _Tp Type of element.
79 * @tparam _Sequence Type of underlying sequence, defaults to deque<_Tp>.
80 *
81 * Meets many of the requirements of a
82 * <a href="tables.html#65">container</a>,
83 * but does not define anything to do with iterators. Very few of the
84 * other standard container interfaces are defined.
85 *
86 * This is not a true container, but an @e adaptor. It holds
87 * another container, and provides a wrapper interface to that
88 * container. The wrapper is what enforces strict
89 * first-in-last-out %stack behavior.
90 *
91 * The second template parameter defines the type of the underlying
92 * sequence/container. It defaults to std::deque, but it can be
93 * any type that supports @c back, @c push_back, and @c pop_back,
94 * such as std::list, std::vector, or an appropriate user-defined
95 * type.
96 *
97 * Members not found in @a normal containers are @c container_type,
98 * which is a typedef for the second Sequence parameter, and @c
99 * push, @c pop, and @c top, which are standard %stack/FILO
100 * operations.
101 */
102 template<typename _Tp, typename _Sequence = deque<_Tp> >
103 class stack
104 {
105#ifdef _GLIBCXX_CONCEPT_CHECKS
106 // concept requirements
107 typedef typename _Sequence::value_type _Sequence_value_type;
108# if __cplusplus < 201103L
109 __glibcxx_class_requires(_Tp, _SGIAssignableConcept)
110 __glibcxx_class_requires(_Sequence, _BackInsertionSequenceConcept)
111# endif
112 __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept)
113#endif
114
115 template<typename _Tp1, typename _Seq1>
116 friend bool
117 operator==(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
118
119 template<typename _Tp1, typename _Seq1>
120 friend bool
121 operator<(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
122
123#if __cpp_lib_three_way_comparison
124 template<typename _Tp1, three_way_comparable _Seq1>
126 operator<=>(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
127#endif
128
129#if __cplusplus >= 201103L
130 template<typename _Alloc>
131 using _Uses = typename
133
134#if __cplusplus >= 201703L
135 // _GLIBCXX_RESOLVE_LIB_DEFECTS
136 // 2566. Requirements on the first template parameter of container
137 // adaptors
139 "value_type must be the same as the underlying container");
140#endif // C++17
141#endif // C++11
142
143 public:
144 typedef typename _Sequence::value_type value_type;
145 typedef typename _Sequence::reference reference;
146 typedef typename _Sequence::const_reference const_reference;
147 typedef typename _Sequence::size_type size_type;
148 typedef _Sequence container_type;
149
150 protected:
151 // See queue::c for notes on this name.
152 _Sequence c;
153
154 public:
155 // XXX removed old def ctor, added def arg to this one to match 14882
156 /**
157 * @brief Default constructor creates no elements.
158 */
159#if __cplusplus < 201103L
160 explicit
161 stack(const _Sequence& __c = _Sequence())
162 : c(__c) { }
163#else
164 template<typename _Seq = _Sequence, typename _Requires = typename
167 : c() { }
168
169 explicit
170 stack(const _Sequence& __c)
171 : c(__c) { }
172
173 explicit
174 stack(_Sequence&& __c)
175 : c(std::move(__c)) { }
176
177#ifdef __glibcxx_adaptor_iterator_pair_constructor // C++ >= 23 && HOSTED
178 template<typename _InputIterator,
179 typename = _RequireInputIter<_InputIterator>>
180 stack(_InputIterator __first, _InputIterator __last)
181 : c(__first, __last) { }
182#endif
183
184#if __glibcxx_ranges_to_container // C++ >= 23
185 /**
186 * @brief Construct a stack from a range.
187 * @since C++23
188 */
189 template<__detail::__container_compatible_range<_Tp> _Rg>
190 stack(from_range_t, _Rg&& __rg)
191 : c(ranges::to<_Sequence>(std::forward<_Rg>(__rg)))
192 { }
193
194 /**
195 * @brief Construct a stack from a range.
196 * @since C++23
197 */
198 template<__detail::__container_compatible_range<_Tp> _Rg,
199 typename _Alloc>
200 stack(from_range_t, _Rg&& __rg, const _Alloc& __a)
201 : c(ranges::to<_Sequence>(std::forward<_Rg>(__rg), __a))
202 { }
203#endif
204
205 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
206 explicit
207 stack(const _Alloc& __a)
208 : c(__a) { }
209
210 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
211 stack(const _Sequence& __c, const _Alloc& __a)
212 : c(__c, __a) { }
213
214 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
215 stack(_Sequence&& __c, const _Alloc& __a)
216 : c(std::move(__c), __a) { }
217
218 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
219 stack(const stack& __q, const _Alloc& __a)
220 : c(__q.c, __a) { }
221
222 template<typename _Alloc, typename _Requires = _Uses<_Alloc>>
223 stack(stack&& __q, const _Alloc& __a)
224 : c(std::move(__q.c), __a) { }
225
226#if __cplusplus > 202002L
227 template<typename _InputIterator, typename _Alloc,
228 typename = _RequireInputIter<_InputIterator>,
229 typename = _Uses<_Alloc>>
230 stack(_InputIterator __first, _InputIterator __last, const _Alloc& __a)
231 : c(__first, __last, __a) { }
232#endif
233#endif
234
235 /**
236 * Returns true if the %stack is empty.
237 */
238 _GLIBCXX_NODISCARD bool
239 empty() const
240 { return c.empty(); }
241
242 /** Returns the number of elements in the %stack. */
243 _GLIBCXX_NODISCARD
245 size() const
246 { return c.size(); }
247
248 /**
249 * Returns a read/write reference to the data at the first
250 * element of the %stack.
251 */
252 _GLIBCXX_NODISCARD
253 reference
255 {
256 __glibcxx_requires_nonempty();
257 return c.back();
258 }
259
260 /**
261 * Returns a read-only (constant) reference to the data at the first
262 * element of the %stack.
263 */
264 _GLIBCXX_NODISCARD
265 const_reference
266 top() const
267 {
268 __glibcxx_requires_nonempty();
269 return c.back();
270 }
271
272 /**
273 * @brief Add data to the top of the %stack.
274 * @param __x Data to be added.
275 *
276 * This is a typical %stack operation. The function creates an
277 * element at the top of the %stack and assigns the given data
278 * to it. The time complexity of the operation depends on the
279 * underlying sequence.
280 */
281 void
282 push(const value_type& __x)
283 { c.push_back(__x); }
284
285#if __cplusplus >= 201103L
286 void
287 push(value_type&& __x)
288 { c.push_back(std::move(__x)); }
289
290#if __cplusplus > 201402L
291 template<typename... _Args>
292 decltype(auto)
293 emplace(_Args&&... __args)
294 { return c.emplace_back(std::forward<_Args>(__args)...); }
295#else
296 template<typename... _Args>
297 void
298 emplace(_Args&&... __args)
299 { c.emplace_back(std::forward<_Args>(__args)...); }
300#endif
301#endif
302
303#if __glibcxx_ranges_to_container // C++ >= 23
304 template<__detail::__container_compatible_range<_Tp> _Rg>
305 void
306 push_range(_Rg&& __rg)
307 {
308 if constexpr (requires { c.append_range(std::forward<_Rg>(__rg)); })
309 c.append_range(std::forward<_Rg>(__rg));
310 else
311 ranges::copy(__rg, std::back_inserter(c));
312 }
313#endif
314
315 /**
316 * @brief Removes first element.
317 *
318 * This is a typical %stack operation. It shrinks the %stack
319 * by one. The time complexity of the operation depends on the
320 * underlying sequence.
321 *
322 * Note that no data is returned, and if the first element's
323 * data is needed, it should be retrieved before pop() is
324 * called.
325 */
326 void
328 {
329 __glibcxx_requires_nonempty();
330 c.pop_back();
331 }
332
333#if __cplusplus >= 201103L
334 void
335 swap(stack& __s)
336#if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11
337 noexcept(__is_nothrow_swappable<_Sequence>::value)
338#else
339 noexcept(__is_nothrow_swappable<_Tp>::value)
340#endif
341 {
342 using std::swap;
343 swap(c, __s.c);
344 }
345#endif // __cplusplus >= 201103L
346 };
347
348#if __cpp_deduction_guides >= 201606
349 template<typename _Container,
350 typename = _RequireNotAllocator<_Container>>
352
353 template<typename _Container, typename _Allocator,
354 typename = _RequireNotAllocator<_Container>>
355 stack(_Container, _Allocator)
357
358#ifdef __glibcxx_adaptor_iterator_pair_constructor
359 template<typename _InputIterator,
360 typename _ValT
362 typename = _RequireInputIter<_InputIterator>>
363 stack(_InputIterator, _InputIterator) -> stack<_ValT>;
364
365 template<typename _InputIterator, typename _Allocator,
366 typename _ValT
368 typename = _RequireInputIter<_InputIterator>,
369 typename = _RequireAllocator<_Allocator>>
370 stack(_InputIterator, _InputIterator, _Allocator)
372#endif
373
374#if __glibcxx_ranges_to_container // C++ >= 23
375 template<ranges::input_range _Rg>
376 stack(from_range_t, _Rg&&) -> stack<ranges::range_value_t<_Rg>>;
377
378 template<ranges::input_range _Rg, __allocator_like _Alloc>
379 stack(from_range_t, _Rg&&, _Alloc)
382#endif
383#endif
384
385 /**
386 * @brief Stack equality comparison.
387 * @param __x A %stack.
388 * @param __y A %stack of the same type as @a __x.
389 * @return True iff the size and elements of the stacks are equal.
390 *
391 * This is an equivalence relation. Complexity and semantics
392 * depend on the underlying sequence type, but the expected rules
393 * are: this relation is linear in the size of the sequences, and
394 * stacks are considered equivalent if their sequences compare
395 * equal.
396 */
397 template<typename _Tp, typename _Seq>
398 _GLIBCXX_NODISCARD
399 inline bool
400 operator==(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
401 { return __x.c == __y.c; }
402
403 /**
404 * @brief Stack ordering relation.
405 * @param __x A %stack.
406 * @param __y A %stack of the same type as @a x.
407 * @return True iff @a x is lexicographically less than @a __y.
408 *
409 * This is an total ordering relation. Complexity and semantics
410 * depend on the underlying sequence type, but the expected rules
411 * are: this relation is linear in the size of the sequences, the
412 * elements must be comparable with @c <, and
413 * std::lexicographical_compare() is usually used to make the
414 * determination.
415 */
416 template<typename _Tp, typename _Seq>
417 _GLIBCXX_NODISCARD
418 inline bool
419 operator<(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
420 { return __x.c < __y.c; }
421
422 /// Based on operator==
423 template<typename _Tp, typename _Seq>
424 _GLIBCXX_NODISCARD
425 inline bool
426 operator!=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
427 { return !(__x == __y); }
428
429 /// Based on operator<
430 template<typename _Tp, typename _Seq>
431 _GLIBCXX_NODISCARD
432 inline bool
433 operator>(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
434 { return __y < __x; }
435
436 /// Based on operator<
437 template<typename _Tp, typename _Seq>
438 _GLIBCXX_NODISCARD
439 inline bool
440 operator<=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
441 { return !(__y < __x); }
442
443 /// Based on operator<
444 template<typename _Tp, typename _Seq>
445 _GLIBCXX_NODISCARD
446 inline bool
447 operator>=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
448 { return !(__x < __y); }
449
450#if __cpp_lib_three_way_comparison
451 template<typename _Tp, three_way_comparable _Seq>
452 [[nodiscard]]
454 operator<=>(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y)
455 { return __x.c <=> __y.c; }
456#endif
457
458#if __cplusplus >= 201103L
459 template<typename _Tp, typename _Seq>
460 inline
461#if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11
462 // Constrained free swap overload, see p0185r1
464#else
465 void
466#endif
467 swap(stack<_Tp, _Seq>& __x, stack<_Tp, _Seq>& __y)
468 noexcept(noexcept(__x.swap(__y)))
469 { __x.swap(__y); }
470
471 template<typename _Tp, typename _Seq, typename _Alloc>
472 struct uses_allocator<stack<_Tp, _Seq>, _Alloc>
473 : public uses_allocator<_Seq, _Alloc>::type { };
474#endif // __cplusplus >= 201103L
475
476_GLIBCXX_END_NAMESPACE_VERSION
477} // namespace
478
479#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:524
Define a member typedef type only if a boolean constant is true.
Definition type_traits:134
Declare uses_allocator so it can be specialized in <queue> etc.
Definition memoryfwd.h:75
A standard container using fixed-size memory allocation and constant-time manipulation of elements at...
Definition stl_deque.h:792
A standard container giving FILO behavior.
Definition stl_stack.h:104
void pop()
Removes first element.
Definition stl_stack.h:327
size_type size() const
Definition stl_stack.h:245
void push(const value_type &__x)
Add data to the top of the stack.
Definition stl_stack.h:282
bool empty() const
Definition stl_stack.h:239
const_reference top() const
Definition stl_stack.h:266
stack()
Default constructor creates no elements.
Definition stl_stack.h:166
reference top()
Definition stl_stack.h:254