c++ - Does resizing an STL vector erase/invalidate its previous contents? -


it doesn't appear (sample program), can sure?

// resizing stl vector erase/invalidate it's previous contents? #include <stdio.h> #include <vector> using namespace std ;  void print( vector<int>& t ) {   for( int = 0 ; < t.size() ; i++ )     printf( "%d ", t[i] ) ;   puts(""); }  int main() {   vector<int> t ;   t.resize( 12,9999 ) ;   print(t) ;    t.resize( 15, 10000 ) ;   print(t) ; } 

resizing stl vector may require reallocating underlying storage. may cause number of elements destroyed , recreated, , all iterators invalidated. accessing invalidated iterator common source of errors when using stl.

the contents of each element same, unless copy constructor doesn't work.

int main(int argc, char *argv[]) {     int data[] = { 1, 2, 3 };      std::vector vec(data, data + 3);     // vector contains 1, 2, 3      std::vector::iterator = vec.begin();     cout << *i << endl; // prints 1     int &ref = *i;     cout << ref << endl; // prints 1      vec.resize(6, 99);     // vector contains 1, 2, 3, 99, 99, 99      // wrong! may crash, may wrong thing, might work...     // cout << *i << endl;      // wrong! invalid reference     // cout << ref << endl;      return 0; } 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -