Returning a pointer
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//returns a pointer to a string element
string* ptrToElement(vector<string>* const pVec, int i);
int main()
{
vector<string> v;
v.push_back("A");
v.push_back("B");
v.push_back("C");
cout << *(ptrToElement(&v, 0)) << endl;
string* pStr = ptrToElement(&v, 1);
cout << *pStr << endl;
string str = *(ptrToElement(&v, 2));
cout << str << endl;
*pStr = "Healing Potion";
cout << v[1] << endl;
return 0;
}
string* ptrToElement(vector<string>* const pVec, int i)
{
//returns address of the string in position i of vector that pVec points to
return &((*pVec)[i]);
}
Related examples in the same category