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.