Created
January 8, 2020 11:50
-
-
Save raheemazeezabiodun/14020bcf4b9dc4a76cd0540c3327324b to your computer and use it in GitHub Desktop.
Different ways of looping through a vector in c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
different ways of looping through a vector in c++ | |
*/ | |
#include <iostream> | |
#include <vector> | |
#include <numeric> // for style_four | |
using std::cout; | |
using std::vector; | |
int style_one(vector<int> v) | |
{ | |
int sum = 0; | |
for(int i : v) | |
sum += i; | |
return sum; | |
} | |
int style_two(const vector<int> v) | |
{ | |
int sum = 0; | |
for(int i = 0; i < v.size(); ++i) | |
sum += v[i]; | |
return sum; | |
} | |
int style_three(const vector<int> &v) | |
{ | |
int sum = 0; | |
for(auto i = v.begin(); i != v.end(); ++i) | |
sum += i; | |
return sum; | |
} | |
int style_four(const vector<int> &v) | |
{ | |
return std::accumulate(v.begin(), v.end(), 0); | |
} | |
int main() | |
{ | |
vector<int> v {1, 2, 3}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment