Tips for saving and deleting pointer Data Types in Vector

Source: Internet
Author: User
When using remove or erase to delete elements when saving the pointer type of the class in vector, it is necessary to prevent memory leakage. Generally, elements stored in the vector are manually new objects. These objects must be manually destroyed to prevent memory leakage.
The remove or erase of vector only clears the pointer from the vector, and copies the remaining elements to generate a new vector object, which is not responsible for clearing the object itself. Therefore, delete is required.
If the pointer type is a base class, define a virtual destructor for the base class.

# Include <iostream>
# Include <vector>
# Include <Yut/string. h>

Class ...{
Public:
A (int A): A ()...{}
Virtual ::~ A ()...{
Cerr <"222" <Endl;
}
Int;
};



Vector <A * >:: iterator get (vector <A *> & SS, int key )...{
Vector <A * >:: iterator it = ss. Begin ();
Cerr <"key:" <key <Endl;
Cerr <"SS size:" <ss. Size () <Endl;
While (it! = Ss. End ())...{
Cerr <"(* It)-> A:" <(* It)-> A <Endl;
If (* It)-> A = Key )...{
Return it;
}
It ++;
}
Return ss. End ();
}


Void main ()...{

Vector <A *> a_p;
Int idx = 10;
While (idx> 0 )...{
A * P = new A (idx );
A_p.push_back (P );
Idx --;
}

Int key = 3;
Vector <A *>: iterator it = get (a_p, 3 );
If (it! = A_p.end ())...{
Delete * it;
A_p.erase (it );
} Else ...{
Cerr <"not found" <Endl;
}

}

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.