2013-12-16 46 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()。謝謝你的幫助! –