Advertisement
cwchen

[C++] Reference demo

Aug 27th, 2017
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.46 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3.  
  4. using std::vector;
  5. using std::cout;
  6. using std::endl;
  7.  
  8. int sum(vector<int> &);
  9.  
  10. int main() {
  11.     vector<int> vec {1, 2, 3};
  12.  
  13.     // Pass the reference of vec into sum
  14.     int s = sum(vec);
  15.  
  16.     cout << s << endl;
  17.     cout << vec[1] << endl;
  18.     return 0;
  19. }
  20.  
  21. int sum(vector<int> &vec) {
  22.     int sum = 0;
  23.  
  24.     for (auto ptr = vec.begin(); ptr != vec.end(); ptr++) {
  25.         sum += *ptr;
  26.     }
  27.  
  28.     return sum;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement