Skip to content

Instantly share code, notes, and snippets.

@juehan
Created September 2, 2012 13:59
Show Gist options
  • Select an option

  • Save juehan/3599168 to your computer and use it in GitHub Desktop.

Select an option

Save juehan/3599168 to your computer and use it in GitHub Desktop.
C++11 coding style - default param, std algorithm, non-member function begin() and end()
#include <vector>
#include <algorithm>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::vector;
using std::string;
class Person
{
private:
int _age;
string _name;
public:
//1. Prefer default parameters than overloading
/*
Person(int age, string name) : _age(age), _name(name){}
Person(int age) : _age(age), _name(""){}
Person(string name) : _age(1), _name(name){}
*/
Person(int age=1, string name="") : _age(age), _name(name){}
/*
void GetOld() {
_age++;
}
void GetOld(int n){
_age += n;
}
*/
void GetOld(int n=1){
_age += n;
}
//When you implement in separate cpp, then follow below practices
//void Person::GetOld(int n/*=1*/)
//{
// _age += n;
//
//}
};
int main(int argc, char* argv[])
{
vector<int> vInt(20); //without size when it's initialized, it will be crashed
int i = 0;
//vInt must pre-determin its size before it called in begin() and to be filled in generate_n function
// also, size of the container must be matched with the size used in generate_n function.
//2. Prefer std::generate to fill in arbitary container as it's more expressive and readable
std::generate_n(begin(vInt), 10, [&i](){
return i++;
});
std::generate_n(begin(vInt)+10, 10, [&i](){
return i++;
});
std::for_each(begin(vInt), end(vInt), [](int element){
cout<<element<<endl;
});
//3. Prefer use standard algorithm as it become more powerful with C++11's lambda expression
//all_of
bool areAllItemsLessThan10 = std::all_of(begin(vInt), end(vInt), [](int n){
return (n < 10);
});
cout<<(areAllItemsLessThan10?"Less Than 10" : "Bigger than 10")<<endl;
//any_of
bool isAnyOf9 = std::any_of(begin(vInt), end(vInt), [](int n){
return n==9;
});
cout<<(isAnyOf9?"There is 9":"There is no 9")<<endl;
//none_of
auto biggerThan10 = [](int n){
return n > 10;
};
bool noneOfbiggerThan10 = std::none_of(begin(vInt), end(vInt), biggerThan10);
cout<<(noneOfbiggerThan10?"There is none of bigger than 10":"There is one of bigger than 10")<<endl;
//4. with the help of non-member function begin() and end() that introduced in C++11,
// we can get iterator of c-array either.
int intArr[] = {0,1,2,3,4,5,6,7,8,9};
std::for_each(std::begin(intArr), std::end(intArr), [](int n){
cout<<n<<endl;
});
return 0;
}
/*
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Bigger than 10
There is 9
There is one of bigger than 10
0
1
2
3
4
5
6
7
8
9
Press any key to continue . . .
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment