如何用std向量初始化std栈? [英] How to initialize std stack with std vector?
问题描述
我需要将 std :: vector
放入 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.
我已经尝试Jens回答,但它没有工作。
I have tried Jens answer but it didn't work.
推荐答案
std :: stack
没有接受迭代器的构造函数,因此您可以构造一个临时 deque
并使用以下语句初始化堆栈:
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()) );
}
但是,这会将每个元素复制到容器中。为了获得最大的效率,您还应该使用move-semantics来删除副本。
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) );
}
这篇关于如何用std向量初始化std栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!