Thursday, May 1, 2008

Solution to Day 3 problem.

View the problem statement here.

This problem is very simple, yet I have included it because I want the readers to start using some STL in their C++ programs.

What is STL?
It stands for Standard Template Library. This library has a lot of classes and functions that can replace a lot of data structures and algorithms that we use on a regular basis.

In order to solve our problem we can use the following algorithm
1. Set height[0] as RES
2. Loop through height, from begin to end
if current_element in height is < RES
set RES to current_element

3. Return RES


So, how do we use STL to do this?
We use STLs Algorithms.

--------------------------------------------------------
#include<algorithm>
#include<vector>

int minHeight(vector<int> height)
{
return *min_element(height.begin(),height.end()) ;
}
--------------------------------------------------------

OK OK, that seems to be too much too soon.
So lets break it down.

Q1. Whats that vector thingy? We were supposed to have an array as an input!
Ans. Vector is an STL class. Vectors are a replacement for Arrays. The <int> tells that its an array of int(s).

Q2. What is min_element?
Ans. min_element is a pre-defined* function in algorithm.h that returns a pointer to the minimum element in a specified range.

Q3. So height.begin(), height.end() are ranges right?
Ans. Exactly. height.begin() returns a pointer to the beginning of the array and height.end() returns a pointer to 1 past the end of the array. Between begin() and end() we have covered the whole array.

We will be talking a lot about using STL subsequently.
You can try the program out and let me know if there are any doubts.


* functions are declared not defined in header files. They are defined in the respective libraries.

Note: In reality, min_element() returns something called an iterator which is similar to a pointer and you don't have to bother much about it right now. STL is a very simple to use library with easy syntax, but the way it is taught in books is a bit daunting. So don't bother much about the syntax if you are reading it for the first time. Just see a few examples and learn from them.

2 comments:

Unknown said...

hey again..... this was something new.... i dnt really hav much idea abt templates.... ummm we hav a chapter on templates this sem so i'll try learning it as well as i can.... thanx alot. i really like the way u write solutions to the proble

full_metal said...

Thanks Satbir.
We shall be talking a great deal about STL in the days to come.