Advertisement
spacechase0

Pointers

Oct 25th, 2011
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. std::vector< std::string > vec;
  2.  
  3. std::string str( "Hello World!" ); // 1
  4. vec.push_back( str ); // 2
  5.  
  6. std::string  str2 = vec[ 0 ];  // 3
  7. std::string& str3 = vec[ 0 ];  // 4
  8. std::string* str4 = &vec[ 0 ]; // 5
  9.  
  10. std::vector< std::string >::iterator it; // 6
  11. it = vec.begin(); // 7
  12.  
  13. std::string  str5 = ( * it );  // 8
  14. std::string& str6 = ( * it );  // 9
  15. std::string* str7 = &( * it ); // 10
  16.  
  17. /*
  18. 1. The original string
  19. 2. A copy of 1 is put into vec
  20.  
  21. 3. A copy of the string stored in vec (2)
  22. 4. A reference to the string in vec (2)
  23. 5. A pointer to the string in vec (2)
  24.  
  25. 6. An empty iterator
  26. 7. An iterator pointing to the string in vec (2)
  27.  
  28. 8. A copy of the string pointed to by it (7)
  29. 9. A reference to the string pointed to by it (7)
  30. 10. A pointer to the string pointed to by it (7)
  31.     'it' isn't an actual string. It's a thinly wrapped pointer.
  32.     But, it doesn't implicitly convert to a pointer, so we can't
  33.     just do std::string* ptr = it;.
  34.    
  35.     Instead, you'll need to convert it to a reference to a string
  36.     (which is '( * it )'), and then get the address (which is
  37.     '&( * it )'). If you try '&it', you are getting the address
  38.     of the iterator, not the string. But in an iterator, the
  39.     '( * it )' operator is overloaded to return a reference to
  40.     the object it points to.
  41. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement