Work/C++

vector 의 iterator 사용시 주의할 사항

sleepiggy 2010. 11. 19. 04:18
typedef struct Custom{ string name; int level; };
vector inputList;
void readCustom(){

ifstream fin("custom.inp");
Custom tempCustom;
vector::iterator it;

while(!fin.eof()) {

fin >> tempCustom.name >> tempCustom.level ; inputList.push_back(tempCustom);

if(inputList.size()==1) {cout<<"first"; it = inputList.begin();}
if(inputList.size()==2) {cout<<"first"; it = inputList.begin(); it++;}
cout<<"size는 " << inputList.size()<<"입니다\n";
cout<< (*it) << endl ; it++;
}
}
custom.inp 에서

kim 2
park 4
choi 1

이런 형식으로 된 자료를 읽어와 벡터에 넣고 확인을 위해 cout 으로 출력을 하는 코드인데,
이 코드가 어째 자꾸 프린트가 제대로 되지 않는 것이였다.
그래서 혹시 값이 안들어가나 해서 inputList.size도 프린트 해보고 하였는데, 계속 안되서 확인을 해보니

vector는 vector에 새로 push_back 을 하거나 erase 등을 하면 iterator 가 무효화가 되어 제대로 동작하지 않는 것이였다.
따라서 push_back 이나 pop_back 혹은 erase 를 한 후에는 꼭 다시 it 를 정의해 주어야 한다!

'Work > C++' 카테고리의 다른 글

구조체의 우선순위 큐 구현  (1) 2010.11.19
list 자료형  (0) 2010.11.03