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

copy array to vector c++
std::copy
vector copy constructor
c++ vector
create copy of a vector
copy vector of vectors c++
c++ clone vector
create a vector from another vector 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);
 }

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

Ways to copy a vector in C++, Ways to copy a vector in C++ But Vector classes has more than one methods to copy entire vector into other in This method is a general method to copy, in this method a loop is used to push_back() the old vector elements into new vector. in C++ (5 different ways) · Different methods to copy in C++ STL | std::copy(),  v1 vector elements are : 7 6 4 5 v2 vector elements are : 7 6 4 5 3) By assignment “=” operator. It is a simple way to copy values from vector 1 to vector 2. Algorithm Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assignment operator “=” to copy the elements of v1 to v2. Print the elements of v1.

Some fun with stacks demonstrating various methods of getting values onto the stack from another container.

Assuming we provided an appropriate definition for:

template<class T, class Container>
auto stack_pusher(std::stack<T, Container>& stack);

We could then write:

int main()
{
    using namespace std;

    // construct an initial vector
    vector<int> init { 7,6 };

    // construct a stack using a copy of the initial vector's elements
    // note that the stack's storage is automatically deduced
    stack<int> stack1 { { begin(init), end(init) } };

    // construct a stack directly from a container initialised with an initialiser list
    stack<int> stack2 { { 3,4,5 } };

    // another vector
    vector<int> myvector { 1, 2, 3, 4, 5, 6, 7, 8 };

    // copy vector onto stack using a forward iterator
    copy(begin(myvector),
         end(myvector),
         stack_pusher(stack1));

    // copy vector onto stack using a reverse iterator
    copy(rbegin(myvector),
         rend(myvector),
         stack_pusher(stack2));

    // display the stacks
    while (stack1.size() or stack2.size())
    {
        // function to encode an optional T as a string
        auto encode = [](const auto& opt)
        {
            return opt ? std::to_string(opt.value()) : std::string("*");
        };

        // function to pop a value from a stack if it's not empty.
        // return an optional
        auto maybe_pop = [](auto& stack)
        {
            using element_type = std::decay_t<decltype(stack.top())>;
            boost::optional<element_type> result;
            if (stack.size()) {
                result = stack.top();
                stack.pop();
            }
            return result;
        };

        cout
        << encode(maybe_pop(stack1))
        << "\t"
        << encode(maybe_pop(stack2)) << endl;
    }

    return 0;
}

for which the output would be:

8       1
7       2
6       3
5       4
4       5
3       6
2       7
1       8
6       5
7       4
*       3

Here's the full listing (c++14):

#include <iostream>
#include <stack>
#include <vector>
#include <deque>
#include <iterator>
#include <utility>
#include <boost/optional.hpp>

// an iterator that pushes values onto a stack
template<class Stack>
struct push_iterator
: std::iterator<std::output_iterator_tag,void,void,void,void>
{
    push_iterator(Stack& stack)
    : pstack(std::addressof(stack))
    {}

    template<class T>
    auto& operator=(T&& t)
    {
        pstack->push(std::forward<T>(t));
        return *this;
    }

    auto& operator*() {
        return *this;
    }

    auto& operator++() {
        return *this;
    }

private:
    Stack* pstack;
};

// convenience class to make a push_iterator of the correct type
template<class T, class Container>
auto stack_pusher(std::stack<T, Container>& stack)
{
    return push_iterator<std::stack<T, Container>>(stack);
}

int main()
{
    using namespace std;

    // construct an initial vector
    vector<int> init { 7,6 };

    // construct a stack using a copy of the initial vector's elements
    // note that the stack's storage is automatically deduced
    stack<int> stack1 { { begin(init), end(init) } };

    // construct a stack directly from a container initialises with an initialiser list
    stack<int> stack2 { { 3,4,5 } };

    // another vector
    vector<int> myvector { 1, 2, 3, 4, 5, 6, 7, 8 };

    // copy vector onto stack using a forward iterator
    copy(begin(myvector),
         end(myvector),
         stack_pusher(stack1));

    // copy vector onto stack using a reverse iterator
    copy(rbegin(myvector),
         rend(myvector),
         stack_pusher(stack2));

    // display the stacks
    while (stack1.size() or stack2.size())
    {
        // function to encode an optional T as a string
        auto encode = [](const auto& opt)
        {
            return opt ? std::to_string(opt.value()) : std::string("*");
        };

        // function to pop a value from a stack if it's not empty.
        // return an optional
        auto maybe_pop = [](auto& stack)
        {
            using element_type = std::decay_t<decltype(stack.top())>;
            boost::optional<element_type> result;
            if (stack.size()) {
                result = stack.top();
                stack.pop();
            }
            return result;
        };

        cout
        << encode(maybe_pop(stack1))
        << "\t"
        << encode(maybe_pop(stack2)) << endl;
    }

    return 0;
}

Different methods to copy in C++ STL, Arrays · Linked List · Stack · Queue · Binary Tree · Binary Search Tree · Heap · Hashing Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), How to initialize Array of objects with parameterized constructors in C++ · How to The new vector elements entered using copy() : 1 5 7 0 0 0 The new vector  Ways to copy a vector in C++ In case of arrays, there is no much choice to copy an array into other, other than iterative method i.e running a loop to copy each element at respective index. But Vector classes has more than one methods to copy entire vector into other in easier ways.There are basically two types of copying :-

std::stack is a strange but hackeable container:

#include<vector>
#include<stack>

struct A{};

template<class T>
struct mystack : std::stack<T>{
    decltype(auto) c(){return std::stack<T>::c;}
};

int main(){
    std::vector<A>  m_vec;

    mystack<A>   m_stack;
    m_stack.c().assign(m_vec.begin(), m_vec.end());

}

or

#include<vector>
#include<stack>

struct A{};

template<class... T>
struct mystack : std::stack<T...>{
    decltype(auto) container(){return std::stack<T...>::c;}
};

template<class... T>
decltype(auto) container(std::stack<T...>& s){return static_cast<mystack<T...>&>(s).container();}

int main(){
    std::vector<A>  m_vec;

    std::stack<A>   m_stack;
    container(m_stack).assign(m_vec.begin(), m_vec.end());
}

std::copy - copy, Copies the elements in the range [first,last) into the range beginning at result . copy algorithm example #include <iostream> // std::cout #include <algorithm> // std::copy int main () { int myints[]={10,20,30,40,50,60,70}; std::vector< int > myvector (7); std::copy C++ · Information · Tutorials · Reference · Articles · Forum  In this post, we will see how to copy a vector in C++. Copying a vector includes constructing a new vector with a copy of each of the elements in original vector, and in the same order. The recommended approach would be to use the copy constructor which internally takes care of all copying. Another solution is to use..

See this question for ways of allowing std::copy to be used on a stack, but out of the box, there is no more obvious way than a loop with calls to push.

As to performance, the only way to tell is to measure it. (Code for clarity and correctness first, and then worry about speed.)

stack::stack - C++ Reference, C++98; C++11 This container object is a copy of the ctnr argument passed to the constructor, if any, otherwise it is an empty container. std::deque< int > mydeque (3,100); // deque with 3 elements std::vector< int > myvector (2,200); initialized to copy of deque std::stack< int ,std::vector< int > > third; // empty stack using  First, let’s not use the term STL. The STL was a library created many, many years ago, and it was absorbed into the C++ standard library during the first rounds of standardization.

Copy a vector in C++, std::copy. The standard algorithm for copying is std::copy . We can use it for copying elements from source vector to the destination vector. But  The general idea behind this is that the vector will always have some spare room to grow into without having to reallocate memory, copy elements, and de-allocate memory every single time. Within the append method you call allocate_to_len() regardless of whether or not more memory is needed.

Can you copy values ​​from a stack to a vector using STL in C++? , So let's just say the standard library. The std::stack container is designed to only give you access to the top element. So normal copy operations  InputIterator shall point to a type assignable to the elements pointed by OutputIterator. n Number of elements to copy. If this value is negative, the function does nothing. Size shall be (convertible to) an integral type. result Output iterator to the initial position in the destination sequence of at least n elements.

C++ Core Guidelines: std::array and std::vector are your Friends , Here is a rule of thumb: If you want to add elements to your container The std::​array is typically created on the stack and the elements of a std::vector are created on the heap. std::vector and std::deque support since C++11 the new method shrink_to_fit. I want to avoid creating copies when converting . Copies the elements in the range [first,last) into the range beginning at result. The function returns an iterator to the end of the destination range (which points to the element following the last element copied). The ranges shall not overlap in such a way that result points to an element in the range [first,last). For such cases, see copy

Comments
  • will a copying be happened here ?
  • @HumamHelfawi: Yes. I assumed the OP wanted that, since she said "I need to copy". You can also move the vector in if you don't need the original any longer.
  • @KerrekSB Thanks, I was just asking not criticizing :) I voted up before commenting;)
  • @basav why not? std::containers are move-aware like almost everything else in the std library
  • @TM: You can't do that other than with a loop, or possibly deriving your own adaptor and adding such a facility. Check the documentation for the (very short) interface to learn what you can and cannot do. If the bill doesn't fit, don't bother using a stack, and just use a vector and operate it like a stack. There's no prize for using std::stack at any cost.