2013-12-16 44 views
-2

我在C++编写的小程序:堆栈与嵌套地图

#include <stack> 
#include <map> 
#include <string> 
using namespace std ; 
int main() { 
    stack< map<string,int> > st ; 
    map<string,int> ma ; 
    st.push(ma) ; 
    ma = st.pop() ; // error here 
    return 0 ; 
} 

但是,编译器显示错误:

no match for ‘operator=’ in ‘ma = st.std::stack<_Tp, _Sequence>::pop<std::map<std::basic_string<char>, int>, std::deque<std::map<std:: 

basic_string<char>, int>, std::allocator<std::map<std::basic_string<char>, int> > > >()’ 

有谁知道什么是错用此代码?

+1

请确保您在发布此类问题之前已详细研究过图书馆参考资料。这是所有[*非常*有据可查](http://en.cppreference.com/w/cpp/container/stack/pop)。 –

+0

对不起,我应该删除这个问题吗? –

+1

由你决定。它肯定有很多重复的东西,并且问题标题对其他人来说不太可能有帮助。 –

回答

2

不幸的是,std::stack::pop将卸下的价值。你必须先分配top值,然后调用pop,在堆栈上,将其删除:

#include <stack> 
#include <map> 
#include <string> 

int main() { 
    std::stack<std::map<std::string, int>> st; 
    std::map<std::string, int> ma; 
    st.push(ma); 
    ma = st.top(); 
    st.pop(); 
    return 0; 
} 

如果你不相信我:here的活例子。

+0

感谢您的帮助! –

1

std::stack<>::pop不返回值。您需要拨打top而不是,然后您称为pop。

ma = st.top(); 
st.pop(); 

实际上,因为你大概要流行元素了,它会如果你使用的是C++ 11最好使用std::move

ma = std::move(st.top()); 
st.pop(); 
+0

对不起,我不想编辑这个我想编辑我的:|不知道如何“回滚” – 111111

+0

哦,对!顺便说一句,最后一行是st.pop()。谢谢你的帮助! –