std::stack<T,Container>:: push
From cppreference.net
|
void
push
(
const
value_type
&
value
)
;
|
(1) | |
|
void
push
(
value_type
&&
value
)
;
|
(2) | (C++11 이후) |
주어진 요소 value 를 스택의 최상단으로 푸시합니다.
1)
동등한 표현:
c.
push_back
(
value
)
.
2)
동등한 표현:
c.
push_back
(
std
::
move
(
value
)
)
.
목차 |
매개변수
| value | - | 푸시할 요소의 값 |
반환값
(없음)
복잡도
Container :: push_back 의 복잡도와 동일합니다.
예제
이 프로그램은 BrainHack DSL 을 구현하며, std::stack 을 사용하는 것이 짝을 이루는 괄호를 처리하는 관용적인 방법입니다.
이 코드 실행
#include <array> #include <cstdint> #include <iostream> #include <map> #include <stack> #include <stdexcept> #include <string_view> class BrainHackInterpreter { std::map<unsigned, unsigned> open_brackets, close_brackets; std::array<std::uint8_t, 32768> data_{0}; unsigned program_{0}; int pos_{0}; void collect_brackets(const std::string_view program) { std::stack<unsigned> brackets_stack; for (auto pos{0U}; pos != program.length(); ++pos) { if (const char c{program[pos]}; '[' == c) brackets_stack.push(pos); else if (']' == c) { if (brackets_stack.empty()) throw std::runtime_error("대괄호 []가 일치하지 않습니다!"); else { open_brackets[brackets_stack.top()] = pos; close_brackets[pos] = brackets_stack.top(); brackets_stack.pop(); } } } if (!brackets_stack.empty()) throw std::runtime_error("대괄호 []가 일치하지 않습니다!"); } void check_data_pos(int pos) { if (pos < 0 or static_cast<int>(data_.size()) <= pos) throw std::out_of_range{"데이터 포인터가 범위를 벗어났습니다!"}; } public: BrainHackInterpreter(const std::string_view program) { for (collect_brackets(program); program_ < program.length(); ++program_) switch (program[program_]) { case '<': check_data_pos(--pos_); break; case '>': check_data_pos(++pos_); break; case '-': --data_[pos_]; break; case '+': ++data_[pos_]; break; case '.': std::cout << data_[pos_]; break; case ',': std::cin >> data_[pos_]; break; case '[': if (data_[pos_] == 0) program_ = open_brackets[program_]; break; case ']': if (data_[pos_] != 0) program_ = close_brackets[program_]; break; } } }; int main() { BrainHackInterpreter { "++++++++[>++>>++>++++>++++<<<<<-]>[<+++>>+++<-]>[<+" "+>>>+<<-]<[>+>+<<-]>>>--------.<<+++++++++.<<----.>" ">>>>.<<<------.>..++.<++.+.-.>.<.>----.<--.++.>>>+." }; std::cout << '\n'; }
출력:
안녕하세요, cppreference!
참고 항목
|
(C++11)
|
최상단에 제자리에서 요소를 생성
(public member function) |
|
최상단 요소를 제거
(public member function) |