Advantages and disadvantages of recursion in C + + application

Source: Internet
Author: User

" recursion " in C + + (C + + training) in the main solution with the tree-like features of the algorithm or data structure, the use of recursion can make the algorithm or data structure greatly simplified, the code is simple and clear, the same subject with this feature recursive or other algorithms, the required predefined and corresponding results will be different, using recursion may be used to reduce the partial definition, the code implementation part greatly reduced, a look at the knowledge. Here is a comparison of the numbers taken from the database:

Data structures used in the implementation (table structure)

Type description of Chinese name in English name

1 ID Permission ID Int

2 parentid parent Permission ID Int to specify parent node

3 Name permission names Varchar (32)

4 idcode menu item ID int permission associated with menu item

From the data structure can be seen, through the ParentID, to implement the tree structure of permissions to describe the hierarchy of permissions, which is a typical tree-type data structure, the use of recursion can simplify the implementation of the program, but through the experiment proves that the simple adoption of recursion will lead to performance deficiencies, The operation effect cannot satisfy the basic operation of the user, and after implementing the recursive algorithm, the program is described in the implementation of recursion.

1, through the tree node memory to achieve false recursion

DWORD dwfunction = 0; Feature ID

The Htreeitem hitemlayer[5][2];//is used to save the currently operating node for backtracking.

int nidcollection[5][2]; The ID of the parent node that identifies the parent layer of the next node

Set Tree roots

Hitemlayer[0][0] = M_treeoperatorpermission.insertitem (_t ("permission Setting"), 3, 3);

M_treeoperatorpermission.setitemdata (Hitemlayer[0][0], dwfunction);

HITEMLAYER[0][1] = hitemlayer[0][0];

Nidcollection[0][0] = 0; Parent Layer ID

NIDCOLLECTION[0][1] = 0; Current Layer ID

int ncurparentlay = 0;

Cadorecordset collection (&m_conn); ADO object for extracting a recordset from a database

CString strsqlstring ("Select ID, ParentID, Name, Idcode from tbl_function order by ID, parentid");

if (collection. Open (strsqlstring))

{int ncount = collection. GetRecordCount ();

CString Strfunctionname;

for (int i = 0;i<ncount;i p= "" + +) <= "" >

{//Remove the node data from the database

Collection. GetFieldValue ("Name", strfunctionname);

int nId;

int Nparentid;

Collection. GetFieldValue ("Id", nId);

Collection. GetFieldValue ("ParentID", Nparentid);

do {

Determines whether the parent node of the reservation is consistent and is used to determine whether to insert a child node from the current insertion point or from the parent node.

if (Nparentid = = Nidcollection[ncurparentlay][0])

{//Inserts a child node into the parent layer and retains the current node data for backtracking

HITEMLAYER[NCURPARENTLAY][1] = M_treeoperatorpermission.insertitem ((LPCTSTR) strfunctionname, 0, 1, hItemLayer[ Ncurparentlay][0]);

NIDCOLLECTION[NCURPARENTLAY][1] = nId;

M_treeoperatorpermission.sethalfchecked (hitemlayer[ncurparentlay][1]);

Dwfunction = nId;

M_treeoperatorpermission.setitemdata (hitemlayer[ncurparentlay][1], dwfunction);

} elseif (Nparentid = = nidcollection[ncurparentlay][1])

{//Create a child layer at the current level

Hitemlayer[ncurparentlay + 1][1] = M_treeoperatorpermission.insertitem ((LPCTSTR) strfunctionname, 0, 1, hItemLayer[nCu RPARENTLAY][1]);

Hitemlayer[ncurparentlay + 1][0] = hitemlayer[ncurparentlay][1];

Nidcollection[ncurparentlay + 1][0] = Nparentid;

Nidcollection[ncurparentlay + 1][1] = nId;

m_treeoperatorpermission.setchecked (Hitemlayer[ncurparentlay + 1][1], FALSE);

Dwfunction = nId;

M_treeoperatorpermission.setitemdata (Hitemlayer[ncurparentlay + 1][1], dwfunction);

Ncurparentlay + +;

} else

{//backtracking to find matching parent nodes for easy insertion of nodes

Ncurparentlay--;

Continue

} break;

}while (TRUE);

Collection. MoveNext ();

} m_treeoperatorpermission.expand (Hitemlayer[0][0], tve_expand);

} collection. Close ();

M_treeoperatorpermission.clearallcheck ();

return 0;

Comment: This method is implemented by means of a State method to implement a recursive method, you can see that the code implementation is quite complex, the programmer must specify the implementation of the process, so that other programmers can read (of course, the comments are supposed to be, here is how to make other programs easier to read code).

This program uses the path of preserving from the parent node to the current node, used to backtrack to find the next node of the parent node, the programmer is a very elaborate, in his walk through the foot to make a label, so that he can go back to recognize the road, but also easy to explore the next road will not repeat the same branch (forming a dead loop).

Advantages: The program uses only one search statement to implement the initialization of the permission tree, reduce the number of database connections, so that performance will be optimal, that is, to achieve the most of the data operation.

Disadvantage: In the review has been said that the complexity of the code, the existence of the code to bring a great possibility, in addition to the data also have certain requirements, must conform to the order can be correctly executed.

2. Application of recursive algorithm

Longinitdefaultpermissiontree (int nparentid, Htreeitem hItem)

{

CString strsqlstring;

Strsqlstring.format ("Select ID, name from tbl_function where parentid =%d", nparentid);

Cadorecordset collection (&m_conn);

if (collection. Open (strsqlstring))

{

Take all data out

CArray Nidarray;

CArray Strnamearray;

int ncount = collection. GetRecordCount ();

for (int i = 0;i < ncount; i + +)

{int nId;

CString StrName;

Collection. GetFieldValue ("id", nId);

Collection. GetFieldValue ("name", StrName);

Collection. MoveNext ();

Nidarray.add (NID);

Strnamearray.add (StrName);

} collection. Close ();

Inserting data from a database into a tree chart

for (i = 0;i < Ncount;i + +)

{int nId = Nidarray.getat (i);

Htreeitem Hsonitem = M_treeoperatorpermission.insertitem (Strnamearray.getat (i), 0, 0, HItem);

M_treeoperatorpermission.setitemdata (Hsonitem, nId);

The following describes the purpose of using M_treedatamap (CMAP)

M_treedatamap.setat (NId, Hsonitem);

Recursive insertion of sub-node data to the current node.

Initdefaultpermissiontree (Nidarray.getat (i), hsonitem);

}} return 0;

}

Comments: In this program simply look, only a loop to complete the data reading and display (this program uses two loops just want to reduce the number of database connections due to recursion), it is obvious that the code is clear and understandable. There is no need for too many annotations to understand the implementation process.

There is no significant number of auxiliary variables in the implementation process to help the structure of the memory tree, as in the first example, which is accomplished by recursive characteristics.

Advantages: Simple and clear, easy to understand, the biggest feature is the implementation of recursion when the default, which is also in the writing of recursive procedures should have the basic idea of understanding, otherwise the programmer will never think that the algorithm can be implemented by recursion.

Disadvantage: The first example has been mentioned in the advantages, in fact, the shortcomings of this example, recursion generated corresponding access to the stack operation and the equivalent of other data (such as database connection number, etc.) will have a negative impact on the performance of the program, especially for more levels of the situation is more serious, Of course, the non-tree features do not advocate the implementation of recursive algorithm, such as the accumulation of 1~100, although the recursive algorithm can be implemented, but it can still be implemented with conventional algorithms, here does not advocate recursive algorithm.

Normal algorithm

int Sum (int nMax)

{int nSum = 0;

for (int I = 1;i <= nmax;i + +)

{NSum + = I;

} return nSum;

} Recursive algorithm

int Sum (int nMax)

{if (NMax > 0)

{return Sum (nmax–1) + NMax;

} else

{return 0;

} }

In summary, the recursive algorithm should be used in some of the conventional algorithm to achieve a more difficult, and recursive features of the algorithm will be used recursive algorithm, otherwise do not recommend a disguised application of recursive algorithm, as described in the subsequent calculation of the accumulation of 1~100, here is the application of a resolutely negative recursive algorithm.

Writing code should consider a variety of factors, including the readability of the code, understandable, simple (this feature has some limitations), performance, and other factors decided.

Recursion is preferred for a low performance requirement but recursion can improve the readability and comprehension of code and greatly simplify the implementation of code.

When performance requirements are high, programmers may be required to replace them with other similar algorithms to ensure performance is preferred, but in some cases, replacing recursion with other algorithms may not necessarily improve the performance of the algorithm, but recursion is the best algorithm (which generally refers to fewer recursive hierarchies).

In short, the use of recursion has its advantages, there are disadvantages, whether the programmer should adopt recursive algorithm in the implementation process, should consider whether the use of recursive algorithm will affect the overall requirements of the relevant modules or systems.

Advantages and disadvantages of recursion in C + + application

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.