   c++ stl vector::insert : how make it work ?
  I''m trying to implement a replace function with STL vector and I dont understant much of the inline docWhat''s wrong with the following code, or how make it work ?   vector<int> list;list.push_back( 1 );list.push_back( 2 );list.push_back( 3 );list.push_back( 4 );vector<int>::iterator it;for (it=list.begin(); it!=list.end(); it++)if (*it == 3){list.erase( it );list.insert( it, 5 );list.insert( it, 5 );} alternate code    vector<int> list;list.push_back( 1 );list.push_back( 2 );list.push_back( 3 );list.push_back( 4 );vector<int>::iterator it;for (it=list.begin(); it!=list.end() && *it != 3 ;it++);if (*it == 3){list.erase( it );list.insert( it, 5 );list.insert( it, 5 );}
  When you erase an item, the iterator pointing to it is not valid anymore. Vectors are somewhat special, becaus even insert can make an iterator invalid if a reallocation happens.So first you should use reserve to allocate memory for the worst case.Why do you erase and then insert at the same position? Just overwrite the 3 with 5, then insert the second 5. ;  replacinglist.erase( it );list.insert( it, 5 );list.insert( it, 5 );byit = list.erase( it );it = list.insert( it, 5 );it = list.insert( it, 5 );should do the trick...;int values[4] = { 1, 2, 3, 4 };vector<int> list(values, values+4);for (int i=0; i<list.size(); i++)if (list[i] == 3){list[i] = 5;list.insert(list.begin()+i, 5);} [edit: oopsed]   [edited by - fractoid on February 19, 2004 8:33:56 AM];  VolkerG : that''s maybe the reason for my program to crash.grumlin : I didn''t know we could do soThanks guys !!What about insert_iterators ? Are they worthy ?What other STL classes do you use ? ;  Also, sort of OT, and it won't make or break your program, but prolly not good idea to name a variable 'list', especially when it is s variable of type 'vector', as both vector and list are STL containers.  Can confuse other programmers lookin at your stuff.  But again, this is sort of just a sufelli comment. [edited by - stonicus on February 19, 2004 10:41:39 AM];  quick note, always _preincrement_ iterators instead of postincrementing. that way you don''t create a temporary iterator that get''s junked anyway. short: it''s more efficient to write ++it then it++ on iterators (and classes to, normally. but the built in types like int etc doesn''t matter)   }-- Programmer/Gamer/Dreamer --{I didn''t choose to code, coding choose me. ;  The compiler tends to optimize away the temporary when using the post-increment (postcrement?) operator, so if you''re bothering about the creation of a temporary, use it for PODs too. ;  you have a semi-colon after the for loop. It stop the ''if'' from being in the loop. 