0

Is there any problem to put c++ iterator into queue? For example:

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()));
}
John
  • 193
  • 2
  • 14
  • 2
    Be very careful what you do with the vectors afterwards. `std::vector` tends to invalidate its iterators at a drop of a hat. – Igor Tandetnik Dec 26 '16 at 06:52

2 Answers2

2

Iterators may be invalidated if you modify the variable vecs.

For more details, refer to iterator invalidation rules.

Community
  • 1
  • 1
Oscarzhao
  • 75
  • 1
  • 9
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;
}

This code could give an explanation for the problem.

  • This answer would benefit from a clear summary. Also, there are typos in the code -- I recommend you clean it up with the help of an [online compiler](http://coliru.stacked-crooked.com). Finally, [please don't recommend the use of `using namespace std;`](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Quentin Dec 26 '16 at 09:57