将c ++迭代器放入队列中

时间:2016-12-26 06:48:56

标签: c++11

将c ++迭代器放入队列有什么问题吗?例如:

vector<vector<int>> vecs;
queue<pair<vector<int>::iterator, vector<int>::iterator>> mq;
for (auto &e : vecs)
{
    mq.push(make_pair(e.begin(), e.end()));
}

2 个答案:

答案 0 :(得分:2)

如果修改变量vecs,则迭代器可能会失效。

有关详细信息,请参阅iterator invalidation rules

答案 1 :(得分:0)

#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
#include<utility>

using namespace std;
vector<vector<int>> vecs;
queue<pair<vector<int>::iterator, vector<int>::iterator>> mq;

void populate_vector()
{
    for(int i = 0;i<6;++i)
    {
        for(int j =0;j<6;++j)
        {
            vecs[i].push_back(i+j);
        }
    }
}
void print_queue()
{
    queue<pair<vector<int>::iterator, vector<int>::iterator>> :: iterator qiter = begin(mq);qiter != end(mq);++qiter)
        cout<<"*qiter.first"<<*qiter.first<<"*qiter.second"<<*qiter.second<<endl;
}   
void print_vector_run_time_error(vector<vector<int>> cont){

    try{    
        for(int i =0;i<6;++i)
        {
            for(int j =0;j<6;++j)
            {
                cout<<cont[i][j]<<" ";
            }
            cout<<endl;
        }
        }
    catch(exception &e){

        cout<<e.what();
    }

}

int main()
{

    for (auto &e : vecs)
    {
        mq.push(make_pair(e.begin(), e.end()));
    }
    /*
        if the below 3 function calls were not present,compilation and  running happens successfully .
        This code creates problems at compile or run time as described below (whenever memory is accessed and iterators are invalidated).
    */

    print_queue();
    /*
        gives a compile time error as the compiler does not recognize a call to vector<int>::iterator as iterator is not a container
    */

    populate_vector();
    /*
    the above function compiles successfully but terminates at run time , because memory is accessed during run time to fill the 
    elements with a value(C++11 vector is populated always at run time).
    */

    print_vector_run_time_error(vecs);

    /* above function call to print vector compiles successfully , but terminates at run time  
    because memory is accessed at run time to print the value of the elements.
    */


    return 0;
}

此代码可以解释此问题。