The 3rd chapter of library function, which is about the problem of library function, is introduced in this chapter. Using library functions can reduce the difficulty of software development and improve the efficiency of code writing. This section introduces the misuse of the Multiset container erase function.
Ad:51cto Net + 12th salon: The beauty of big data-how to drive user experience with data
Misuse of erase function of 3.16 multiset container
code example
- int main () {
- Multiset <int> c1;
- C1.insert (3);
- C1.insert (2);
- C1.insert (3);
- C1.insert (3);
- C1.insert (5);
- int x=3;
- C1.erase (x);//remove one element with value 3
- for (Multiset <int>::iterator it = c1.begin (); It! = C1.end (); it++)
- {
- cout << *it << Endl;
- }
- return 0;
- }
Phenomena & Consequences
The code expects to delete an element with a value of 3, but the actual running result shows that all elements with a value of 3 are deleted.
Bug Analysis
There are two types of erase function prototypes with one parameter multiset. One is to pass an element value, as in the example code above, when all the values in the collection are equal to the input values, and the number of deleted elements is returned, and the other is to pass a iterator that points to an element, at which point the corresponding element is deleted, and no return value is removed. The user needs to correctly invoke the corresponding prototype according to their own application scenario. The intent of the example code is to delete an element, but it actually removes all elements with a value of 3, which is not expected.
Correct code
- int main () {
- Multiset <int> c1;
- C1.insert (3);
- C1.insert (2);
- C1.insert (3);
- C1.insert (3);
- C1.insert (5);
- int x=3;
- Multiset <int>::iterator pos = c1.find (x);
- C1.erase (POS);//remove one element with value 3
- for (Multiset <int>::iterator it = c1.begin (); It! = C1.end (); it++) /c7>
- {
- cout << *it << Endl;
- }
- return 0;
- }
Programming recommendations
When using multiset, it is important to note that the main difference between Mutilset and the normal set container is that Multiset allows elements to be duplicated, and set does not allow elements to be duplicated. This can have a different effect on some operations.
Misuse of Multiset container erase function