In C ++, the STL container type is used as a function and does not use references, which leads to a decrease in program efficiency. stl containers

Source: Internet
Author: User
Tags types of functions

In C ++, the STL container type is used as a function and does not use references, which leads to a decrease in program efficiency. stl containers

I recently found a problem with algorithm questions:

I implement an algorithm recursively, but in the TreeNode * createTree Function(Vector <int> & num, Int left, int right)

TreeNode * createTree (Vector <int> num, Int left, int right), The result always times out,

I found some algorithms written by others on the Internet and found that they are all implemented in that way. Finally, I found that the parameter types of functions are different,

When someone else uses the vector type as a parameter, the reference is passed, and I directly use the form parameter of the function, resulting in every function recursion, all the values of the num array must be copied, which greatly affects the program efficiency.

Finally, I changed it to use reference, which greatly improved the efficiency of the result program!


Summary:

When parameters such as vector, queue, and stack are involved in c ++,Be sure to use & as parametersOtherwiseData Copying, Resulting in a much lower efficiency of the entire program!

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.