2017-11-29 2 views
-1

queue<vector<int>>期待どおりに動作しません。私はpop()の後にvectorへの参照にアクセスできない。予期しないC++キューの動作、ポップ後にオブジェクトを失う

#include <vector> 
#include <cstdio> 
#include <queue> 
#include <iostream> 

using namespace std; 

struct TreeNode { 
    string val; 
    TreeNode(string x) : val(x) {} 
}; 

int main() { 

    queue<int> q = {}; 


    q.push(1); 
    q.push(2); 

    int& test = q.front(); 
    q.pop(); 
    // queue<int>; front() and then pop() behaves as expected 
    cout << "test1 " << test << " expect: 1" << endl; 

    TreeNode n1("node a"); 
    TreeNode n2("node b"); 
    queue<TreeNode> q2 = {}; 


    q2.push(n1); 
    q2.push(n2); 

    TreeNode& test2 = q2.front(); 
    q2.pop(); 

    // queue<TreeNode>; front() and then pop() behaves as expected  
    cout << "test2 " << test2.val << " expect: node b" << endl; 


    vector<int> v1 = {0,1,2}; 
    vector<int> v2 = {2,3,4}; 

    queue<vector<int>> q3 = {}; 

    q3.push(v1); 
    q3.push(v2); 
    vector<int>& test3 = q3.front(); 
    // front() alone returns what I expected 
    cout << "test3 size " << test3.size() << " expect: size 3" << endl; 

    vector<int>& test4 = q3.front(); 
    q3.pop(); 
    // however front() and then pop() does not behave as expected  
    cout << "test4 size " << test3.size() << " expect: size 4" << endl; 
    return 0; 
} 

出力:

test1 1 expect: 1 
test2 node a expect: node b 
test3 size 3 expect: size 3 
test4 size 0 expect: size 4 

Process finished with exit code 0 

質問:

上記の例で任意のコードのにおいはありますか?私はいつもpop()の後に参照を失うことを期待する必要がありますか? pop()の後に参照を使用しないでください。

またはvectorは特殊なケースですか?

EDIT: knowing that dangling reference is always bad practice. I made some changes to the code and now have some follow up questions.

フォローアップの質問は:

queue<int> q = {}; 
q.push(1); 
q.push(2); 
// making a copy here 
// follow up question 1: is this now correct? 
int test = q.front(); 
q.pop(); 


vector<int> v1 = {0,1,2}; 
vector<int> v2 = {2,3,4}; 

queue<vector<int>> q3 = {}; 

q3.push(v1); 
q3.push(v2); 

// I am trying to make a copy here but the compiler complains: 
// Parameter type mismatch: expression must be rvalue 
// follow up question 2: why can't I make a copy of the vector but I can make a copy of the int in the previous example? 
vector<int> test3 = q3.front(); 
q3.pop() 
+4

もちろん、あなたは参照を失っています。 'pop()'の後、キューの先頭にある元の要素への参照は、決して決して決して陸にならないような参照となり、それをテキストブックで定義されていない振る舞いにします。あなたは正確に何について不明ですか? –

+0

同じ質問を継続的に拡張するのではなく、新しい質問の新しい質問を投稿する必要があります。あなたが行う場合は、MCVE –

答えて

3

あなたはオブジェクトへの参照を格納し、オブジェクトを破壊しています。 popをキューから外すと、キューにはもう存在しません。オブジェクトのコピーを作成するか、完了するまでpopしないでください。

もう一度存在しないオブジェクトにアクセスしようとしないでください。結果は予測できません。

+0

を投稿するので、偶数キューの例が間違っていますか?それは、定義されていない動作なので、私は何とか 'test1'で探していたintを見つけることができますか? – samol

+0

'int'が存在しなくなったので、' test1'で探していたintを見つけられない可能性があります。あなたは、起こった価値観を見たことがあります。しかし、それは何が起こったかのようにあなたの期待の事故である。 (なぜあなたは値が同じままであると思いますか?) –

+1

@samol:はい、 'queue 'の例も間違っています。何が参照しているかにかかわらず、ダングリングリファレンスは常に間違っています –

関連する問題