Search and delete vector and map in STL

Source: Internet
Author: User

Currently, vector and map are the two most commonly used containers in STL. When using vector or map, we will find and delete them in the container as needed. The following summarizes the correct results in the actual test.

 

Search:

The find function is used for map search.

Map <int, cstring >:: iterator ITER;

Iter = mapintstring. Find (1 );

If (ITER! = Mapintstring. End ())

{

// Todo:

}

The find function does not exist in the vector and can only be searched through traversal.

Vector <int> vecnum;

For (uint I = 0; I <vecnum. Size (); I ++)

{

// Use vecnum [I] For comparison

}

 

Delete:

If you do not use the iterator, you can delete the vector directly.

Vector <int> m_vecnum;

 

M_vecnum.push_back (1 );

M_vecnum.push_back (2 );

M_vecnum.push_back (3 );

 

For (uint I = 0; I <m_vecnum.size (); I ++)

{

If (m_vecnum [I] = 1)

{

M_vecnum.erase (& m_vecnum [I]);

Break;

}

}

Int num = m_vecnum [I];

The result num value is 2.

When deleting a map, the map must use an iterator. When deleting a map, it involves the iterator pointer.

For example:

Map <int, cstring> mapintstring;

 

Cstring strtext;

Strtext. Format ("string1 ");

Mapintstring. insert (make_pair (1, strtext ));

Strtext. Format ("string2 ");

Mapintstring. insert (make_pair (2, strtext ));

Strtext. Format ("string3 ");

Mapintstring. insert (make_pair (3, strtext ));

 

Map <int, cstring >:: iterator ITER;

Iter = mapintstring. Find (1 );

If (ITER! = Mapintstring. End ())

{

Mapintstring. Erase (ITER );

}

Int num = ITER-> first;

In this case, the ITER address has been deleted, so the last num has no value.

The correct method is as follows:

Map <int, cstring >:: iterator ITER;

Map <int, cstring >:: iterator iterdel;

Iter = mapintstring. Find (1 );

If (ITER! = Mapintstring. End ())

{

Iterdel = ITER;

ITER ++;

Mapintstring. Erase (iterdel );

}

Int num = ITER-> first;

The value is correct. The value of num is 2.

 

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.