Advertisement
sanjay1909

Vector Elements Reference

May 16th, 2014
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. // Vector Methods returns the Value not reference
  2.  
  3. /*
  4. * Code to explain the issue
  5. * Followed by modified version of same code , to meet my requirements
  6. */
  7.  
  8.  
  9. vector<string> stringVector;
  10. string one = "one";
  11. string two ="two";
  12.  
  13. cout << "Address-1 : " << &one << endl; //Address-1 : 0x28fec0
  14. cout << "Address-2 : " << &two << endl; //Address-2 : 0x28febc
  15.  
  16. stringVector.push_back(one);
  17. string* LastElementAddress = &stringVector.back();
  18. cout << "1 :  at Address: " << LastElementAddress << endl; //1 :  at Address: 0x5d4a08
  19. stringVector.push_back(two);
  20. LastElementAddress = &stringVector.back();
  21. cout << "2 :  at Address: " << LastElementAddress << endl; //2 :  at Address: 0x5d4a2c
  22.  
  23.  
  24. //To access the reference of Vector elements , prefer storing the address, that value
  25. /*
  26. * In the below code
  27. * I modified the above code to support reference for the inner elements
  28. */
  29. vector<string*> stringVector;
  30. string* one = new string("one");
  31. string* two = new string("two");
  32.  
  33. cout << "Address-1 : " << one << endl; //Address-1 : 0x782238
  34. cout << "Address-2 : " << two << endl; //Address-2 : 0x784a08
  35.  
  36. stringVector.push_back(one);
  37. string* LastElementAddress = stringVector.back();
  38. cout << "1 :  at Address: " << LastElementAddress << endl; // 1 :  at Address: 0x782238
  39. stringVector.push_back(two);
  40. LastElementAddress = stringVector.back();
  41. cout << "2 :  at Address: " << LastElementAddress << endl; //2 :  at Address: 0x784a08
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement