把C++迭代器放入隊列有什麼問題嗎?例如:把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()));
}
把C++迭代器放入隊列有什麼問題嗎?例如:把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()));
}
如果修改變量vecs
,則迭代器可能失效。請參閱iterator invalidation rules。
#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;
}
此代碼可以給出問題的解釋。
這個答案會從清晰的總結中受益。此外,代碼中還有拼寫錯誤 - 我建議您在[在線編譯器](http://coliru.stacked-crooked.com)的幫助下清理它。最後,[請不要推薦使用'using namespace std;'](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Quentin
以後要非常小心你用矢量做什麼。 'std :: vector'傾向於使其迭代器在一滴帽子中無效。 –