C ++ starts from scratch (8) - C ++ sample one

zhaozj2021-02-16  86

C from zero (8) - C sample precedentary to the partial implementation method, but not explained the semantics of the syntax of the function, that is, what is used in the function and why it is used. For this reason, this article and subsequent zero will be mentioned in "C from scratch (12)". This article is just the basic requirements of the programmer - the algorithm is obtained, give the code - some samples to explain how to write C code from the algorithm and explain multiple bases and important programming concepts (ie independent The concept of programming language). It is the case where the code is started by the algorithm, and it means that the program (not compatible due to the CPU's world and the objective physical world of the objective physical physics world, "is to translate the program (that is, algorithm) into the CPU directive, However, in order to be translated, it is necessary to make people feel that some things in the CPU world are some things described in the algorithm. Such as pictures displayed on the computer screen, showing different colors via the monitor to the different colors, and people think that is a picture, and the computer only knows that a series of numbers, each number represents a color value of a pixel. In order to achieve the above "people feel", the first step to do after the algorithm is to find the resources to operate in the algorithm. As mentioned earlier, any program describes how to operate resources, and the C language itself can operate the value of the memory, so the first step in programming is to map the things that operate in the algorithm into memory values. . Since the value of the memory unit and the continuity of the memory cell address can be expressed by the binary number, the first step to do is to indicate what the other in the algorithm is expressed. The first step in the above is equivalent to mathematical modeling - the problem is expressed in mathematical language, and it is only used to represent the resource operated by digital (should pay attention to the difference between numbers, numbers in C ) It is an operator that has a related type. Since it is finally calculated or the binary number, it is used to enhance the semantic). The second step is to map all the operations of the resource in the algorithm into statements or functions. When expanding the algorithm in the mathematical language, for example, the number of people who will be 10 minutes to the station in the station into a random variable, which is also the first step. The random variation is then distributed from the Poisson distribution, that is, the second step. The number of people who arrive at the station is the resource that is operated, and the algorithm given is a random value that changes this resource every 10, turn its value into a random value distributed in the Poisson function of the given parameter. In C , the resource has been mapped to a number, then the operation of the resource is to be mapped to a logarithmic operation. The operation of the number can operate in C is only operators, which is to map all the operations of the resource in the algorithm into an expression statement. When the above is completed, the remaining in the algorithm is only in the order, and the execution order is written from the top of the C , and when the intervention of logic judgment changes, the previous IF and GOTO statement (but the latter can also be implemented by the back of the IF, this can reduce the use of the GOTO statement, because the semantics of GOT are jumping instead of "so"), and can consider whether to use a cyclic statement to simplify Code. That is, the third step is to expand the execution process.

The second step in the previous steps can also be mapped into a function, that is, some operation is more complicated, with logical means, can not directly find the corresponding operator, then take advantage of the universal function operator, for this Operation Repeat the three steps just above to map this operation into multiple statements (with statements that use IF to show the logic information), and the statement is defined as a function, and the function operator is used to represent that operation. The above is not tight, and there are two examples later, how each of the above steps is performed separately. Sort three cards, three integers were written casually. There are three boxes, respectively from 1, 2 and 3, respectively. Randomly put three cards in the three boxes of 1, 2, 3, now demand sorted to make the integers in the three boxes of 1, 2, 3 in the order of small to large. A simple algorithm is given: the integers on the card placed in 1, 2, and 3 boxes are first, second, three, respectively, first compare the first number and the second number, if the former is large The card exchange in two boxes; then the first and third comparisons, if the former is exchanged, so that the first number is minimal. The second number and the third number are then compared, and if the former is exchanged, it is sorted. Step 1: The resources operated in the algorithm are cards mounted in the box. In order to map this card into a number, it will pay attention to what cards in the algorithm and cards before the card. The only way to distinguish between different cards is the integer written on the card, so it is used here to represent a card. There are three cards in the algorithm, so use three numbers. As mentioned earlier, the numbers are installed in memory, not in variables, and variables are only mapping addresses. The three long type numbers are required here, and the compiler automatically assigns these numbers when the compiler is allocated on the stack, so that three variables Long A1, A2, A3 can be defined in this way; Equivalent to three boxes of three cards. Step 2: The operation in the algorithm is the comparison and exchange of integers on the card. The former is very simple and can be implemented using the logical operator (because the integer on the card is just mapped into the numbers recorded in variables A1, A2, and A3). The latter is a card in two boxes, which can first take a card from a box, put on the table or elsewhere. Then take the card in another box to the box that is just empty. Finally, the card will be taken into the box that is just ever. The "table or elsewhere" in the table is used to store the tethered card, and only the memory can be stored in C , so the above must be allocated a number of temporary memory comes.

Step 3: Operation and resources have been mapped, if there is any IF replacement, how many times is replaced, how to repeat it, use while or do while replace, The algorithm is mapped over, as follows: void main () {long A1 = 34, A2 = 23, A3 = 12; if (a1> a2) {long TEMP = A1; A1 = A2; A2 = Temp;} IF A1> A3) {long TEMP = A1; A1 = A3; A3 = TEMP;} IF (A2> A3) {long TEMP = A2; A2 = A3; A3 = Temp;}} The above is over the following composite A temporary variable TEMP is defined in the statement to provide the memory of the temporary storage card with the static allocation of the compiler. The above element exchange is not mapped in the previously mapped, because there is only three statements here and is easy to understand. If you want to define the switching operation as a function, you should follow: Void Swap (long * p1, long * p2) Void SWAP (long & r1, long & r2) {{long TEMP = * p1; long TEMP = R1; * P1 = * P2; R1 = R2; * P2 = Temp; R2 = TEMP;}} void main () void main () {{long a1 = 34, A2 = 23, A3 = 12; long A1 = 34, A2 = 23, A3 = 12; if (A1> A2) IF (A1> A2) SWAP (& A1, & A2); SWAP (A1, A2); IF (A1> A3) IF (A1> A3) SWAP (& A1, & A3); SWAP (A1, A3); IF (A2> A3) IF (A2> A3) SWAP (& A2, & A3); SWAP (A2, A3);}} First look at the procedure on the left.

The function is defined above to indicate the exchange operation between the given box. Note that the parameter type uses long *, where the pointer represents reference (should pay attention to the pointer not only the reference, but also other semantics will be mentioned later). What is a reference? Note that this is not referred to as the reference variable proposed by C , the reference represents a connection relationship. For example, if you have a mobile phone, the mobile phone number is a reference to "talking to you", that is, you can implement "and your call" as long as you have your mobile phone number. For example, a shortcut provided by the Windows operating system, which is a reference to a "Operation of a file", which can point to a file, able to "execute" the file it refers to the file by double-click this shortcut icon. (It may be to open this file with a software or do this file directly, but if you delete this shortcut, it does not delete the files you point to, because it is just a reference to a file. The name of the person is a reference to "someone who logizes", that is, someone can know which person can know which person. Similarly, variables are also referenced, it is a reference to a block because it maps the address, and the memory block can be unique to the only indication, not just identifier. Note that it is different from the previous name, because any of the operations of the memory block, just know the first address of the memory block, and talk to someone to face or eat, only knowing his name is not enough. It should be noted that there is more than one reference to a certain thing. If people can have multiple names, and the variables have reference variables, and the mobile phone number can also be more than one. Note that the function is introduced into the exchange, which in turn has caused the box to map into a number. The front of the box is mapped to the number of long-type numbers. Due to the "installation" operation, it is conceivable to use the number of memory blocks that can identify the numbers of a representative card as a digital type of the box mapping, that is The first address of the memory block, that is, the LONG * type (note is not the address type, because the number of address types do not return the address of the memory recorded). So the above function parameter type is long *. Look at the right of the right side below. The parameter type becomes Long &, and the pointer, it still represents reference, but pay attention to them. The latter indicates that it is an alias, ie it is a mapping, the address of the map is the address of the number of parameters, that is, when it is asking to call this function, the number given as a parameter is a number of addresses. The so-called "addressable number" indicates that this number is created by programmers, not an address generated by the compiler due to temporary reasons, such as SWAP (A1 , A2); Previously, because the address returned by A1 is set inside the compiler, in terms of program logic, it does not exist, while SWAP ( A1, A2); is correct. SWAP (1 3, 34); still want to report an error, because the memory of the number returned by 1 3 is the internal allocation of the compiler, and the program is logically recorded by the programmer with a block of memory, also There will be no memory. A very simple judgment rule is that the parameter type given when the call is called if it is the number of the address type, otherwise it will not.

It should also be noted that the above is the long & type, indicating that the modified variable does not allocate memory, that is, the compiler is static to set the address of the parameters R1, R2 map, for SWAP (A1, A2); it is A1 and A2 Address, but for SWAP (A2, A3); turn the address of A2 and A3, which is not possible to determine the address of R1, R2 map, that is, R1, R2 maps are changing at operation. It is still not possible to determine when it cannot be compiled. In order to implement the above requirements, the compiler will actually allocate memory on the stack, then pass the address to the function, then write the code to make the address of R1, R2. This is the same as the same effect as long *, that is, the same SWAP (Long &, Long &); and Swap (long *, long *); is the same, only the syntax writing is different, the interior is the same, Lienity is the same, both represent references (although pointers are not just semantics with references). That is, when the function parameter type is a reference type, the memory is still allocated to deliver the address of the parameters, ie equivalent to the pointer type as parameters. Merchants crossing the river, 3 servants crossing the river, crossing the river, only a boat, only two people crossing the river, including boating people. On any side of the river, as long as the number of servants exceeds the number of merchants, the servant will jointly kill the merchants and robbed their belongings, and ask how to design the river's order to make everyone safely over the other side of the river. Give the weakest but universal algorithm - enumeration method. Possible probing as a boat crossing the river and rowing is a servant, a businessman or two businessmen, two servants and a businessman a servant. Therefore, each time you select a row of rivers from the above-mentioned programs, then check the number of people on the riverbank, see if the servant killed the business, if there is no two sides, then choose from the five programs described above One is coming back, and then check if a servant will kill business people. If you don't return to the river from five programs, if you repeat until everyone cross the river. In addition to ensuring that the businessman is not killed, it is necessary to ensure that the program is running (ie, the river is returned), and the number of people on both sides has never appeared, otherwise it will form an unlimited cycle, and must be reasonable, that is, No negative number. If there is a scheduled selection failed, return it back to reallo another solution. If all the scenarios fails, returns to the next scheme selection. If you have been retired to the first scheme selection, and there is no optional solution, the topic is unprofable. The above algorithm has proposed two basic and important concepts - hierarchical and containers. The container will be explained below. Container is installing something, while the things operating in C have only numbers, so the container is a number of things, which is memory. The container can install multiple things on the usual understanding, which can be loaded with multiple numbers. This is very simple, the concept of using the previous array. But if a box can install a lot of apples, then it must account for a lot of volume, that is, no matter whether it is equipped with an apple or two apples, the box will account for half cubic meters. The array is like a box, regardless of an element or two elements, it is a type of long [10] and 40 bytes. The container is used to install things, then things to take out the container in the container, there must be something to identify the container in the container. For arrays, this thing is the subscript of arrays, such as long a [10]; a [3 ], The value of the fourth element is taken out.

Because of the identification, there is a means to indicate which identifier is effective, as the A array above, only the two elements record numbers, but A [3];, the resulting will be the value of the error, Because only A [0] and A [1] are meaningful. Therefore, there is a lot of problems with the array of containers above, but it is very simple and can reflect the order relationship between each element, such as an array after the elements are sorted. However, in order to adapt to the complex algorithm, other containers must be supported, such as linked lists, trees, queues, etc. They are generally also known as a collection, which are used to manage multiple elements, and each gives it to quickly find the elements corresponding to the given identifier from many elements, and can form a kind of elements. Relationship, as the hierarchical relationship, the order relationship of the previous array will be mentioned later. For specific implementations of those containers, please refer to other information, here you don't. In the above algorithm, "The number of people on the branches has never appeared", in order to achieve this, it is necessary to map the resources - the number of people layout into numbers, and all the number of people who have appeared will be recorded. That is to be recorded in a container, since the concept is not not explained, this container is implemented here. The above mentioned that one of the existing schemes is also mentioned, and the optional scheme is also a container, which is the same, still using an array. Hierarchical, ie, the relationship, such as XXX, such as the three-year class of hope elementary school, China's Chengdu's XXX, etc., all show a hierarchical relationship, this level relationship is the relationship between multiple elements, so it can pass Find a container, the elements of the container are already a hierarchical relationship, and this container represents a hierarchical relationship. Tree This container is designed specifically. "Re-retransmission to the next program choice" in the above algorithm, that is, the first cross-river chooses a businessman who has a servant of a businessman, then select a businessman backward, if you choose two The servant's approach will be wrong, and the river will be reselected. Hip that all the rivers in all the rivers have failed, and only backwards back to reselect back, if you choose a servant. For this reason, since it only requires returning to the last state, it is the number of layouts and selection, which can be put in the container, and they only rely on the order relationship, that is, the second approach to the river. It must be considered under the premise of the success of the first cross-river program, so this array is used in the container with sequential relationships. Step 1: The resources of the above algorithms have two: the plan of the ship and the number of people on both sides. Up to five of the boat, here use a char type number to map it, that is, the first 4 digits of this 8-bit binary number uses the complement format to explain the number of the number represents the number of servants, the last 4 digits represent the businessman quantity. So a businessman and a servant are (1 << 4) | 1. The number of people on both sides, the number of businessmen and the number of servants, the number of servants, because the total number of 3 3 = 6 people can use the number of char types to map, but only one number of people can only be mapped, and the number of people on both sides is actually 4 (The number of business people on the left and right sides and the number of servants), then use a char [4] here (the actual use structure is used to map instead of char [4], the following description). Such as Char A [4]; represents a number of layouts, then A [0] represents the number of business people on the left side of the river, A [1] indicates the number of servants on the left, and A [2] represents the number of businessmen on the right side of the river, A [ 3] Indicates the number of servants on the right. Note that the container mentioned earlier, and there should be a container in order to install an optional seat, using an array, such as Char SLN [5];

Here, you also need to record the use of the boat scheme. Since the elements of the array have a sequential relationship, do not regenerate into a container, directly use a char number to record a subscript, when this number is 3, indicating SLN [0], SLN [ 1] and SLN [2] have been used and failed, and currently available for SLN [3] and SLN [4]. Similarly, in order to assemble the number of people after successful seat, it is necessary to use two containers in this case, using arrays (actually should be launched) Char OldLayout [200] [4], CUR [200] ;. OldLayout is a container that records successful scheme, which is 200, indicating that it is within 200, and must have been result, otherwise it will occur because of the upper limit of the array, why is it possible? C will be explained from zero (fifteen) ". As mentioned earlier, this container cannot determine the effective element inside, and must rely on the outside world to determine, in this, using a unsigned char cursln; to record the number of effective elements in OldLayout and Cur. When Cursln is 3, it means OldLayout [0] [0 ~ 3], OldLayout [1] [0 ~ 3] and OldLayout [2] [0 ~ 3] are effective, the same CUR [0], CUR [1] And Cur [2] is valid, and later, as Cur [3] is invalid. Step 2: Operation: Performing a river program, executing a return plan, checking whether the plan is successful, returning to the last program choice, whether everyone has crossing the river, and the number of people is the same. As follows: The first two operations: minus the current number of the current left banks minus the number of claims, and the number of people in the right bank. To express the current left bank, you can use OldLayout [Cursln] [0] and OldLayout [curSln] [1], and the number of people according to the corresponding scheme is (SLN [Cur [Cursln] & 0xF0) >> 4 and SLN [CUR [CURSLN]] & 0xF. Since these two operations are very similar, only one is the other one is minus, so it is defined as a function, and the variables such as OldLayout, Cursln are required to be a global variable in order to operate OldLayout, Cursln in the function. Check if it is successful: 即 即 是 o ouout [curd] [1]> OldLayout [cursln] [0] && oldlayout [curdlayout [0] and whether OldLayout [Cursln] [3]> OldLayout [Cursln] [2] && OldLayout [ Cursln] [2] and guarantees that the negative numbers are negative and there is no conflict with the original program. Check if the original scheme is the same as that all original schemes are compared to the current solution. Due to complicity, it is defined as a function, by returning the BOOL type to indicate whether conflicts. Return to the previous program or to the next option, only CURSLN- or Cursln can be used. Whether everyone crosss the river, only use OldLayout [Cursln] [0 ~ 1] to 0 and OldLayout [CURSLN] [2 ~ 3] is 3. The determination is the same, and it is only necessary to use the corresponding elements. Step 3: There is no thing left below, just need to follow the order of the algorithm, and pay attention to the operations, and pay attention to "repeating until everyone has passed the river" to do while.

As: #include // Represents a businessman, a servant, two businessmen, two servants, a businessman a servant char SLN [5] = {(1 << 4), 1, (2 << 4) <4), 2, (1 << 4) | 1}; Unsigned Char Cursln = 1; Char OldLayout [200] [4], CUR [200]; Void Dosolution (char b) {unsigned long Oldsln = Cursln - 1 ; // Temporary variable, for efficiency OldLayout [Cursln] [0] = OldLayout [OLDSLN] [0] - B * ((SLN [cur [cursln]】 & 0xf0) >> 4); OldLayout [cursln] [1 ] = OldLayout [oldsln] [1] - b * (SLN [cur [cursln]] & 0xf); OldLayout [cursln] [2] = OldLayout [oldsln] [2] b * ((SLN [CUR [Cursln] ] & 0xf0) >> 4); OldLayout [cursln] [3] = OldLayout [OLDSLN] [3] b * (SLN [cur [cursln]] & 0xf);} Bool berepeated (Char b) {for (unsigned Long i = 0; i

// Since the Cur is a global variable, in the VC, it has been assigned to 0 // Reason, which is involved in the data section, which does not table DO {DOSOLUTION (B); if ((OldLayout [Cursln] [1]> OldLayout [ Cursln] [0] && OldLayout [Cursln] [0]) || (OldLayout [Cursln] [3]> OldLayout [Cursln] [2] && OldLayout [Cursln] [2]) || OldLayout [cursln] [0] <0 || OldLayout [Cursln] [1] <0 || OldLayout [Cursln] [2] <0 || OldLayout [Cursln] [3] <0 ||leated (b)) {// Reselection this time Program P: Cur [Cursln] ; IF (CUR [CURSLN]> 4) {b = -b; cur [cursln] = 0; cursln--; if (! Cursln) Break; // No solution P; // Recheck to ensure the validity of CUR [curSln]} Continue;} b = -b; cursln ;} while (! (Oldlayout [cursln - 1] [0] == 0 && OldLayout [cursln - 1] [1] == 0 && OldLayout [cursln - 1] [2] == 3 && Oldl Ayout [CURSLN - 1] [3] == 3)); for (i = 0; i

转载请注明原文地址:https://www.9cbs.com/read-16272.html

New Post(0)