Let's see how Stanford taught students to program.

Source: Internet
Author: User
Tags isearch

Reprinted please indicate the source

Author: Pony

I recently watched the <programming sentence actions> course at Stanford University, and thought that one of the courses was very good. It was about 50 minutes ago, only one course can give me a deep understanding of the difference between computer education in Chinese universities and the United States.

 

I can recall how I spoke C or C ++ when I was studying at school. I remember that I had hardly ever heard of a few lines of code from my teacher. I read them on PPT.

 

Stanford teaches how to use C to implement a general linear lookup function. The so-called generic function is to find any type of data. in C ++, templates can be used. If C is used for implementation, pointers can only be used. Therefore, this course uses a specific application to help students better understand pointers. (If I remember correctly, I took the C language for college exams. the pointer is out of the exam Scope !!!!)

 

This teacher only writes some important code implementation. I will add some application code and some necessary explanations here to organize the core of the entire course into a blog, hoping to help you understand it, in particular, I hope to inspire students who have not yet graduated from the computer science field.

 

All of the following programs are successfully debugged under Visual Studio 2008.

 

Let's take a look at how this linear lookup function is implemented, as shown below:

void *ISearch(void *key,  void *base, int n, int elementSize,     int (* Compare)(void *, void *)){ int i = 0; void *pTmp = NULL; for (i = 0; i < n; i++) {  pTmp = (char *)base + i*elementSize;  if (Compare(key, pTmp) == 0)  {   return pTmp;  } } return NULL;}

 

This function is easy to understand. The first parameter is a pointer to the element to be searched, the second is the base address of the search range, and the third parameter is the size of each element, such as the int type, 4 On a 32-bit machine. the fourth parameter is used to pass in a function pointer. The function is used to compare whether the element to be searched is equal to one element in the search sequence. different implementations are available for different data types.

 

 

First, let's look at the simplest application. In an integer array, find whether an integer number exists. The main function is written like this:

int _tmain(int argc, _TCHAR* argv[]){ int nArray[] = {3, 1, 45, 22, 0, 4}; int n = 6; int key = 22; int *findPosition = ISearch(&key, nArray, n, sizeof(int),  IntCompare); if (findPosition == NULL) {  printf("can not find the key!/n"); } else {  printf("find the key %d!/n", *findPosition); } return 0;}

 

The idea is clear. input the corresponding parameters according to the Isearch interface definition. Now the only thing to do is to implement the comparison function. This is also very simple, as shown below:

int IntCompare(void *element1, void *element2){ int *pTmp1 = element1; int *pTmp2 = element2; return (*pTmp1 - *pTmp2);}

 

 

Here we will increase the difficulty of searching for floating-point numbers. The principle is the same. The difficulty is increased because floating-point numbers require some special processing in an hour. Let's look at the main function first.

int _tmain(int argc, _TCHAR* argv[]){ double nArray[] = {3.01, 1.00, 45.045, 22, 0, 4.1}; int n = 6; double key = 4.099999; double *findPosition = ISearch(&key, nArray, n, sizeof(double),  DoubleCompare); if (findPosition == NULL) {  printf("can not find the key!/n"); } else {  printf("find the key %lf!/n", *findPosition); } return 0;}

 

The doublecompare function is doing some special processing, because the computer cannot accurately represent floating point numbers, because the computer uses discrete data volumes and can only represent floating point numbers within a certain range of precision. therefore, we cannot directly use a comparison operator to operate floating point numbers. we can set a threshold value that specifies that the absolute value of the difference between two floating point numbers is smaller than this threshold value, and the two numbers are considered equal.

Int doublecompare (void * element1, void * element2) {double dlimit = 0.000001; // compare the threshold value, int nret = 0; double * ptmp1 = element1; double * ptmp2 = element2; if (* ptmp1-* ptmp2)> dlimit) {nret = 1;} else if (* ptmp1-* ptmp2) <dlimit) & (* ptmp1-* ptmp2)>-dlimit) {nret = 0 ;}else {nret =-1 ;}return nret ;}

 

 

To further increase the difficulty, the application of the string is as follows:
A string array:
Char * strarrany [] = {"AB", "bcddeee", "# *", "FB "};

Check whether char * strkey = "FB" is in this string.
This usage is very different from the previous two. In the first two applications, the element in the array is the value itself. For example, in an integer array, the element is an integer. in the string array, the elements in the array are indeed not strings, but pointers to these strings. therefore, the size of each element in the array is actually the pointer size, that is, sizeof (char *). it is important to understand this.

If I represent a string array in the following figure, it may be helpful to understand:

 

As shown in the figure, each element in the string array is a pointer, so the size of one of its elements is sizeof (char *). then let's look at the first parameter of Isearch, which is to pass the address of the element to be searched. the pointer is no exception, so the first parameter is in the form of & strkey.

Understanding the above, it is easy to write the main function.

int _tmain(int argc, _TCHAR* argv[]){ char *strArrany[] = {"ab", "Bcddeee", "#*", "fB"}; int n = 4; char *strKey = "fB"; char *findPosition = ISearch(&strKey, strArrany, n, sizeof(char *),  StrCompare); if (findPosition == NULL) {  printf("can not find the key!/n"); } else {  printf("find the key %s!/n", *findPosition); } return 0;}

 

The most difficult part to understand is to compare functions. Its implementation is as follows:

int StrCompare(void *element1, void *element2){ char *pTmp1 = *(char **)element1;  char *pTmp2 = *(char **)element2; return strcmp(pTmp1, pTmp2);}

You may
Char * ptmp1 = * (char **) element1;
This usage is full of doubts. the following describes how to solve the problem step by step. element1 is a pointer. Its parameter is void *, that is, there is no type pointer. Where it points depends on the passed real parameter. in the implementation of Isearch, find the following lines:
If (compare (Key, pTMP) = 0)
{
Return pTMP;
}
The original input is the key, so what is the key? It is the first parameter of the Isearch interface, as follows:
Void * Isearch (void * Key, void * base, int N, int elementsize, INT (* compare) (void *, void *));

 

What is the real parameter that the key points? Find the place where Isearch is called in the main function, as shown below:
Char * strkey = "FB ";
Char ** findposition = Isearch (& strkey, strarrany, N, sizeof (char *), strcompare );

 

Strkey itself is a pointer to a String constant ("FB"), and what is passed to Isearch is & strkey, which is the address of this pointer. therefore, the key is a pointer, And the pointer points to a value. The content on the address pointed to by the pointer is "FB ", so the key is actually a char ** variable, and element1 is also a char ** variable. add another "*", which is the address pointing to "FB" by referencing it.

 

If so, you still cannot understand it. Is it helpful to implement strcompare in another way?

int StrCompare(void *element1, void *element2){ char **pTmp1 = element1; // char **pTmp2 = element2; return strcmp(*pTmp1, *pTmp2);}

If you are a college student, you don't have to worry about understanding this part. I saw the video, and our American students also had a lot of questions about this usage, it seems that everyone's level is still similar. haha. my advice is to practice and think more.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.