returning a reference to a string
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//returns a reference to a string
string& refToElement(vector<string>& v, int i);
int main()
{
vector<string> v;
v.push_back("A");
v.push_back("B");
v.push_back("C");
//displays string that the returned reference refers to
cout << refToElement(v, 0) << "\n\n";
//assigns one reference to another -- inexpensive assignment
string& rStr = refToElement(v, 1);
cout << rStr << "\n\n";
//copies a string object -- expensive assignment
string str = refToElement(v, 2);
cout << str << "\n\n";
//altering the string object through a returned reference
rStr = "Healing Potion";
cout << v[1] << endl;
return 0;
}
string& refToElement(vector<string>& vec, int i){
return vec[i];
}
Related examples in the same category