Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Vector Methods returns the Value not reference
- /*
- * Code to explain the issue
- * Followed by modified version of same code , to meet my requirements
- */
- vector<string> stringVector;
- string one = "one";
- string two ="two";
- cout << "Address-1 : " << &one << endl; //Address-1 : 0x28fec0
- cout << "Address-2 : " << &two << endl; //Address-2 : 0x28febc
- stringVector.push_back(one);
- string* LastElementAddress = &stringVector.back();
- cout << "1 : at Address: " << LastElementAddress << endl; //1 : at Address: 0x5d4a08
- stringVector.push_back(two);
- LastElementAddress = &stringVector.back();
- cout << "2 : at Address: " << LastElementAddress << endl; //2 : at Address: 0x5d4a2c
- //To access the reference of Vector elements , prefer storing the address, that value
- /*
- * In the below code
- * I modified the above code to support reference for the inner elements
- */
- vector<string*> stringVector;
- string* one = new string("one");
- string* two = new string("two");
- cout << "Address-1 : " << one << endl; //Address-1 : 0x782238
- cout << "Address-2 : " << two << endl; //Address-2 : 0x784a08
- stringVector.push_back(one);
- string* LastElementAddress = stringVector.back();
- cout << "1 : at Address: " << LastElementAddress << endl; // 1 : at Address: 0x782238
- stringVector.push_back(two);
- LastElementAddress = stringVector.back();
- cout << "2 : at Address: " << LastElementAddress << endl; //2 : at Address: 0x784a08
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement