How to initialize std stack with std vector?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 18:19:08

问题


I need to put an std::vector into an std::stack.

Here is my method so far(I am building a card game) :

void CardStack::initializeCardStack(std::vector<Card> & p_cardVector) {
   m_cardStack = std::stack<Card>();
   //code that should initialize m_cardStack with p_cardVector
}

Note : I cannot change my method signature because it is a imposed by a teacher...

Do I have to iterate over the whole vector ? What is the most efficient way to do this ? The documentation.

I have tried Jens answer but it didn't work.


回答1:


std::stack doesn't have a constructor which accepts iterators, so you could construct a temporary deque and initialize the stack with this:

void ClassName::initializeStack(std::vector<AnotherClass> const& v) {
   m_stackAttribute = std::stack<AnotherClass>( std::stack<AnotherClass>::container_type(v.begin(), v.end()) );
}

However, this copies each element into the container. For maximum efficiency, you should also use move-semantics to eliminate copies

void ClassName::initializeStack(std::vector<AnotherClass>&& v) {
   std::stack<AnotherClass>::container_type tmp( std::make_move_iterator(v.begin()), std::make_move_iterator( v.end() ));
   m_stackAttribute = std::stack<AnotherClass>( std::move(tmp) );
}



回答2:


The most efficient way is not using an std::stack at all and just use a std::vector or even better for this use a std::deque.

I've seen and written a lot of C++ code (a lot) but I've yet to find any use for the stack stuff (any meaningful use, that is). It would be different if the underlying container could be changed or having its container type determined at runtime, but this is not the case.

To copy the elements from an std::vector into a std::deque you can just use

std::deque<T> stack(vec.begin(), vec.end());

This will allow the implementation to use the most efficient way to copy the elements.

To explicitly answer your question: yes, the only way to put elements in a stack is to push them in with a loop. This is not efficient but the stack interface doesn't define anything else. However who wrote code accepting an std::stack parameter should be fired (unless s/he promises that it will never happen again) and its code reverted to something more sensible: you would get the same (absence of) "flexibility" but a better interface.

The design problem of stack is that it's parametrized on the underlying container type while instead (to have any meaning) should have been parametrized on the contained element type and receving in the constructor a container for that type (thus hiding the container type). In its present form is basically useless.



来源:https://stackoverflow.com/questions/32805250/how-to-initialize-std-stack-with-std-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!