6 Important STL Functions Every Programmer Should Know.

Manas Sinha
The Startup

--

std::sort()

Sorts the array in ascending order. Takes two pointers as parameters, start pointer and the end pointer to the array to be sorted.

vector<int> arr = {2,5,1,0,9,6};
std::sort(arr.begin(),arr.end());
int arr[] = {2,5,1,0,9,6};
std::sort(arr,arr+6);
OUTPUT: 0,1,2,5,6,9

std::reverse()

Reverses the array. Takes two pointers as parameters, Start pointer and the end pointer to the array to be sorted.

vector<int> arr = {2,5,1,0,9,6};
std::reverse(arr.begin(),arr.end());
int arr[] = {2,5,1,0,9,6};
std::reverse(arr,arr+6);
OUTPUT : 6,9,0,1,5,2

std::count()

Counts the number of occurences of a given element in an array. Takes three parameters, Start pointer and the end pointer of the array to be searched and the element to be counted.

vector<int> arr = {2,5,1,0,9,6,5,7,5};
cout<<std::count(arr.begin(),arr.end(),5);
int arr[] = {2,5,1,0,9,6,5,7,5};
cout<<std::count(arr,arr+9,5);
OUTPUT: 3

std::nth_element()

Rearranges the elements in the range [first,last), in such a way that the element at the nth position is the element that would be in that position in a sorted sequence. It takes three parameters, the start pointer, pointer to the nth position, and the end pointer. It also rearranges the array in such a way that the values before n are smaller than arr[n] and values after n are greater than arr[n] .

vector<int> arr = {2,5,1,0,9,6};
std::nth_element (arr.begin(), arr.begin()+3, arr.end());
int arr[] = {2,5,1,0,9,6};
std::nth_element(arr,arr+3,arr+6);
OUTPUT : 1 0 2 5 9 6

std::advance()

Advances the iterator it to to n distance forward if n>0 or backward if n<0. Takes two parameters, the iterator and the value n .

vector<int> arr = {2,5,1,0,9,6};
std::vector<int>::iterator it = arr.begin();
std::advance(it,3);
cout<<(*it);
OUTPUT : 0

std::copy()

Copies the contents of one array to another. Takes three parameter, start and the end pointer of the array to be copied and the start pointer of the output array.

int arr1[] = {2,5,1,0,9,6};
vector<int> arr2(6);

std::copy(arr1, arr1+6, arr2.begin());
for(auto i : arr2){
cout<<i<<" ";
}
OUTPUT : 2,5,1,0,9,6

Things to remeber

The functions mentioned above can not only be applied to the entire container but also a part of it by carefully changing the start pointer and end pointer. for example :

vector<int> arr = {2,5,1,0,9,6,5,5};
cout<<std::count(arr.begin()+2,arr.begin()+6,5);
OUTPUT : 0

Also, I have explained each functions using array as an example, but that can be applied to other containers, but do use your common sense while doing so.

Follow me on facebook and Instagram and visit my website.

--

--

Manas Sinha
The Startup

The thinking process behind solving a problem is much more important than just being able to solve the problem.