Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy elements from std::vector into std::stack c++

I need to copy std::vector into std::stack.

  1. Is traversing over vector and pushing into stack is only the way?

  2. 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);
 }
like image 530
T M Avatar asked Dec 24 '15 12:12

T M


People also ask

How do I move an element from one vector to another in C++?

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.

Is std :: vector on the stack?

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.

How to copy a vector to a vector?

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().


1 Answers

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()));
like image 65
Kerrek SB Avatar answered Oct 22 '22 08:10

Kerrek SB