I need to copy std::vector
into std::stack
.
Is traversing over vector and pushing into stack is only the way?
If there is another way what is better choice from performance point of view?
code:
std::stack<A> m_stack;
std::vector<A> m_vec;
for (auto& elem : m_vec)
{
m_stack.push(elem);
}
Method 4: copy(first_iterator_o, last_iterator_o, back_inserter()) :- This is another way to copy old vector into new one. This function takes 3 arguments, first, the first iterator of the old vector, second, the last iterator of the old vector and third is back_inserter function to insert values from the back.
Although std::vector can be used as a dynamic array, it can also be used as a stack. To do this, we can use 3 functions that match our key stack operations: push_back() pushes an element on the stack. back() returns the value of the top element on the stack.
Algorithm. Begin Initialize a vector v1 with its elements. Declare another vector v2. Make a for loop to copy elements of first vector into second vector by Iterative method using push_back().
Since a stack is a container adaptor, you can create the stack from the underlying container:
std::vector<A> m_vec = /* ... */;
std::stack<A, std::vector<A>> m_stack(m_vec);
Or, if you want your stack to be deque
-backed:
std::stack<A> m_stack(std::deque<A>(m_vec.begin(), m_vec.end()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With