returning a reference to a string : reference « Data Type « C++






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

1.constant references
2.using references for int
3.Reassigning a reference
4.Taking the Address of a Reference
5.swap() Rewritten with References
6.Passing by Reference Using Pointers
7.Passing Objects by Reference
8.Passing References to Objects
9.Returning multiple values from a function using references
10.Creating and Using References for integer
11.Data Slicing With Passing by Value
12.References for int type variable