Skip to content

Instantly share code, notes, and snippets.

View mochow13's full-sized avatar

Mottakin Chowdhury mochow13

View GitHub Profile
body .gist .highlight {
background: #272822;
}
body .gist .blob-num,
body .gist .blob-code-inner,
body .gist .pl-s2,
body .gist .pl-stj {
color: #f8f8f2;
}
body .gist .pl-c1 {
std::vector<int> collection = {3, 6, 12, 6, 9, 12};
// Are all numbers divisible by 3?
// divby3 should equal 1
bool divby3 = std::all_of(begin(collection), end(collection), [](int x) {
return x % 3 == 0;
});
// Is any number divisible by 2?
// divby2 equals true
std::vector<int> collection={2,4,4,1,1,3,9};
// notice that we pass x as reference!
std::for_each(begin(collection),end(collection),[](int &x) {
x=x*26;
});
std::vector<int> collection={1,9,9,4,2,6};
// How many 9s are there in collection?
int nines=std::count(begin(collection),end(collection),9);
// How many elements of the collection are even?
int evens=std::count_if(begin(collection),end(collection),[](int x) {
return x%2==0;
});
// nines equals 2, evens equals 3
std::string mirror_ends(const std::string& in)
{
// mismatch takes two ranges as input, (first1,last1,first2,last2)
// if last2 is not given, it considers first2+(last1-first1) as last2
return std::string(in.begin(), std::mismatch(in.begin(), in.end(), in.rbegin()).first);
}
int main()
{
std::cout << mirror_ends("abXYZba") << '\n'
@mochow13
mochow13 / find_if.cpp
Last active September 15, 2018 04:32
std::vector<int> collection={1,2,0,5,0,3,4};
// itr contains the iterator to the first element following the specific property
auto itr = std::find_if(begin(collection), end(collection), [](int x) {
return x%2==0; // the property
});
std::vector<int> collection={1,2,0,5,0,3,4};
int counter=0;
// notice that we are capturing counter by reference
std::generate(begin(collection), end(collection), [&]() {
return counter++;
});
// collection gets replaced by values starting from 0
// modified collection = {0,1,2,3,4,5,6}
std::vector<int> collection={1,2,13,5,12,3,4};
// rotating to the left
// element at position 3 of the original collection is now the
// first element of the rotated collection
std::rotate(begin(collection), begin(collection)+3, end(collection));
// rotating to the right
// element at position 2 from the end (or at position 4) is now the
// last element of the rotated collection
std::vector<int> collection={1,2,13,5,12,3,4};
std::random_device rd;
std::mt19937 rand_gen(rd());
std::shuffle(begin(collection), end(collection), rand_gen);
std::vector<int> collection={1,2,13,5,12,3,4};
auto median_pos=collection.begin()+collection.size()/2;
std::nth_element(begin(collection),median_pos,end(collection));
// note that the original vector will be changed due to the operations
// done by nth_element