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

Home
C++
1.Bitset
2.Class
3.Console
4.Data Structure
5.Data Type
6.Deque
7.Development
8.File
9.Function
10.Generic
11.Language
12.List
13.Map Multimap
14.Overload
15.Pointer
16.Qt
17.Queue Stack
18.Set Multiset
19.STL Algorithms Binary search
20.STL Algorithms Heap
21.STL Algorithms Helper
22.STL Algorithms Iterator
23.STL Algorithms Merge
24.STL Algorithms Min Max
25.STL Algorithms Modifying sequence operations
26.STL Algorithms Non modifying sequence operations
27.STL Algorithms Sorting
28.STL Basics
29.String
30.Valarray
31.Vector
C / ANSI-C
C Tutorial
C++ Tutorial
Visual C++ .NET
C++ » Data Type » referenceScreenshots 
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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.