fork download
  1. //
  2. // main.cpp
  3. // Iterating over a Vector
  4. //
  5. // Created by Himanshu on 11/12/22.
  6. //
  7.  
  8. #include <iostream>
  9. #include <vector>
  10. using namespace std;
  11.  
  12. void printVectorUsingIndex (vector<int> v) {
  13. int n = (int) v.size();
  14.  
  15. for (int i=0; i<n; i++) {
  16. cout<<v[i]<<" ";
  17. }
  18.  
  19. cout<<endl;
  20. }
  21.  
  22. void printVectorUsingIterator (vector<int> v) {
  23. vector<int>::iterator it;
  24.  
  25. for (it = v.begin(); it != v.end(); it++) {
  26. cout<<(*it)<<" ";
  27. }
  28.  
  29. cout<<endl;
  30. }
  31.  
  32. void printVector (vector<int> v) {
  33.  
  34. for (auto val : v) {
  35. cout<<val<<" ";
  36. }
  37.  
  38. cout<<endl;
  39. }
  40.  
  41. int main () {
  42.  
  43. // Initialisation
  44. vector<int> vec({10, 15, 25, 40, 50});
  45.  
  46. cout<<"Iterating over vector using index:"<<endl;
  47. printVectorUsingIndex(vec);
  48.  
  49. cout<<"Iterating over vector using iterator:"<<endl;
  50. printVectorUsingIterator(vec);
  51.  
  52. cout<<"Iterating over vector using auto:"<<endl;
  53. printVector(vec);
  54.  
  55. return 0;
  56. }
Success #stdin #stdout 0.01s 5428KB
stdin
Standard input is empty
stdout
Iterating over vector using index:
10 15 25 40 50 
Iterating over vector using iterator:
10 15 25 40 50 
Iterating over vector using auto:
10 15 25 40 50