Efficiency of using c ++ vector

Source: Internet
Author: User

1. The efficiency of the erase method in vector is very low. In order to maintain the continuity of elements in the vector in the memory space, after deleting an element, you need to move the elements following it forward one position in sequence, with the average complexity of o (n ). The implementation of erase in gcc under www.2cto.com is as follows: iterator erase (iteratorposition) {if (position + 1! = End () copy (position + 1, finish, position); // move the subsequent elements forward -- finish; destroy (finish ); // return position;} a global function for resource release. Solution: If you want to delete an element at the last position, you do not need to move other elements. You only need o (1) based on this idea, we can implement an efficient method of deleting elements in a vector for (int I = 0; I <vec. size ();) {if (some condition) {swap (vec [I], vec [vec. size ()-1]); vec. pop_back () ;}else {I ++ ;}} 2. the iterator uses vector <int> int_vec; for (vector <int>: iterator iter = int_vec.begin (); iter! = Int_vec.end (); ++ iter ){...} note that you must use ++ iter. You cannot use iter ++ to copy a value first, and then perform ++ with low efficiency.

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.