structCourse{stringcode,doublerating;};autocompRating=[](constauto&s1,constauto&s2){returns1.rating<s2.rating;};size_tsize=classes.size();// O(N) sort, sorts so nth_element is in correct position// all elements smaller to left, larger to rightCoursemedian=*std::nth_element(classes.begin(),classes.end(),size/2,compRating);
Imagine we have a vector of strings, we can use std::stable_partition to partition the vector into two groups(for example cs courses and non-cs courses) without breaking their relative order.
CS61A
CS106L
Math
Physics
English
CS61B
After calling std::stable_partition, we will get two groups:
CS61A
CS106L
CS61B
Math
Physics
English
And std::stable_partition will return an iterator pointing to the first element of the second group.
#include<iostream>#include<vector>usingnamespacestd;intmain(){autoisLessThan5=[](intx){returnx<5;};vector<int>v={1,2,3,4,5,6,7,8,9,10};cout<<"Before remove the size:"<<v.size()<<endl;for(autoi:v){cout<<i<<" ";}cout<<endl;remove_if(v.begin(),v.end(),isLessThan5);cout<<"After remove the size:"<<v.size()<<endl;for(autoi:v){cout<<i<<" ";}}
#include<iostream>#include<vector>usingnamespacestd;intmain(){autoisLessThan5=[](intx){returnx<5;};vector<int>v={1,2,3,4,5,6,7,8,9,10};cout<<"Before remove the size:"<<v.size()<<endl;for(autoi:v){cout<<i<<" ";}cout<<endl;v.erase(remove_if(v.begin(),v.end(),isLessThan5),v.end());cout<<"After remove the size:"<<v.size()<<endl;for(autoi:v){cout<<i<<" ";}cout<<endl;}
Because the Algorithm remove_if is not a member of std::vector (or any other collection). So it doesn't have the ability to remove elements from the vector.
Must be used in conjunction with std::erase to remove the elements.