Skip to content

Instantly share code, notes, and snippets.

@raheemazeezabiodun
Created January 8, 2020 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raheemazeezabiodun/14020bcf4b9dc4a76cd0540c3327324b to your computer and use it in GitHub Desktop.
Save raheemazeezabiodun/14020bcf4b9dc4a76cd0540c3327324b to your computer and use it in GitHub Desktop.
Different ways of looping through a vector in c++
/*
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