Skip to content

Instantly share code, notes, and snippets.

View mochow13's full-sized avatar

Mottakin Chowdhury mochow13

View GitHub Profile
int a=9, b=12;
// out.first contains the minimum element, out.second is the maximum one
auto out=std::minmax(a,b);
std::vector<int> collection={6,5,3,2,1,4,6,7};
auto result=std::minmax_element(begin(collection), end(collection));
// you can also add compare function as the third argument
// (result.first - collection.begin()) is the index of the minimum element
// (result.second - collection.begin()) is the index of the maximum element
@mochow13
mochow13 / heap.cpp
Last active September 15, 2018 08:23
void print_vector(auto &v)
{
std::copy(begin(v), end(v), std::ostream_iterator<int>(std::cout, " "));
std::cout<<'\n';
}
int main()
{
std::vector<int> collection = {3,1,4,1,5,9};
// makes a heap on collection
void merge_sort(auto l, auto r)
{
if(r-l>1)
{
auto mid=l+(r-l)/2;
merge_sort(l,mid);
merge_sort(mid,r);
std::inplace_merge(l,mid,r);
}
}
std::vector<int> c1={1,2,5,5,5,6,9,12};
std::vector<int> c2={2,4,4,5,7,15};
std::vector<int> result; // contains merged elements
std::merge(begin(c1), end(c1), begin(c2), end(c2), std::back_inserter(result));
// result = {1, 2, 2, 4, 4, 5, 5, 5, 5, 6, 7, 9, 12, 15}
// sorted collection
std::vector<int> collection={1,2,5,5,5,6,9,12};
// we are looking for a range where all elements equal to 5
auto range = std::equal_range(begin(collection), end(collection), 5);
// the required range
std::cout<<(range.first-begin(collection))<<" "<<(range.second-begin(collection))<<std::endl;
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
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};
// 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,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}
@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
});