Skip to content

Instantly share code, notes, and snippets.

@skull-squadron
Created March 8, 2024 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skull-squadron/da264091421a000fa8c804da3acbb742 to your computer and use it in GitHub Desktop.
Save skull-squadron/da264091421a000fa8c804da3acbb742 to your computer and use it in GitHub Desktop.
C++ specialization of stack adapter for forward_list
// Specialize stack to work with forward_list (STL singly-linked lists)
// Notes:
// - This is a proof-of-concept as an exercise for template specialization. Don't use in production!
// - Not cache-efficient.
// - Use stack<T, vector<T>> most of the time instead.
// Output
// ======
// t:
// 3
// 2
// 1
// 0
// 7
// 8
// 9
//
// s:
// 50
// 51
// 52
#include <stack>
#include <forward_list>
template <class T>
class std::stack<T, std::forward_list<T>> {
private:
typedef std::forward_list<T> container_type;
typedef std::stack<T, container_type> self;
container_type l_;
public:
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::reference reference;
typedef typename container_type::const_reference const_reference;
explicit stack (const container_type& ctnr) : l_(ctnr) {}
explicit stack (container_type&& ctnr = container_type()) : l_(ctnr) {}
template <class... Args> void emplace (Args&&... args) { l_.emplace_front(args...); }
void push(const_reference val) { l_.push_front(val); }
void pop() { l_.pop_front(); }
bool empty() const { return l_.empty(); }
size_type size() const { return l_.size(); }
reference top() { return l_.front(); }
const_reference top() const { return l_.front(); }
void swap(self& x) noexcept { l_.swap(x.l_); }
};
#include <iostream>
int main() {
std::stack <int, std::forward_list<int>> s({7,8,9});
std::stack <int, std::forward_list<int>> t({50,51,52});
for (int i = 0; i < 4; ++i) s.push(i);
t.swap(s);
std::cout << "t:" << '\n';
for (; !t.empty(); t.pop()) {
std::cout << t.top() << '\n';
}
std::cout << '\n';
std::cout << "s:" << '\n';
for (; !s.empty(); s.pop()) {
std::cout << s.top() << '\n';
}
std::cout << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment