Reputation: 193
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()));
}
Upvotes: 0
Views: 497
Reputation: 75
Iterators may be invalidated if you modify the variable vecs
.
For more details, refer to iterator invalidation rules.
Upvotes: 2
Reputation: 11
#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.
Upvotes: 0