Erase and vectorerase used in vector
As a result of a previous misunderstanding of vector found in the use of the latest project, we found that we do not know much about vect, so we want to write a bit about it.
Attention in vector usage. In this article, we will first talk about the erase function of vector. If there is any error, please point out
First, I wrote a function to print the vector memory and print the content and address of the vector storage data respectively:
void printVec(vector<int> outputVec){ if (!outputVec.empty()) { int nSize = outputVec.size(); for (int i = 0; i < nSize; i++) { printf_s("%d %d\r\n", outputVec.at(i), &(outputVec.at(i))); } } cin.get(); }
Then we start to test the erase function of the vector.
First, we apply for a vector object and press 10 pieces of data into it.
vector<int> myVec;cout<<"push_back VEC"<<endl;for (int i = 0; i <10; i++){ myVec.push_back(i);}printVec(myVec);
Delete it in the wrong way, that is, the method I used previously
vector<int>::iterator itePre; cout<<"erase VEC in wrong way"<<endl; for (itePre = myVec.begin(); itePre != myVec.end(); itePre++) { myVec.erase(itePre); } printVec(myVec);
According to my previous understanding, the expected results of such a loop deletion method should be to clear the data in the vector, but this is not the case.
The program crashes.
Because the itePre iterator itself is unpredictable after being erase and should not be used again.
For this reason, I modified the Code as follows:
vector<int>::iterator itePre; cout<<"erase VEC in wrong way"<<endl; for (itePre = myVec.begin(); itePre != myVec.end(); itePre++) { itePre = myVec.erase(itePre); } printVec(myVec);
The result is not that I want to clear all the data.
But only half of the data is deleted. Why?
In MSDN, the returned values for erase are described as follows:
Return Value
An iterator that designates the first element remaining beyond any elements removed, or a pointer to the end of the vector if no such element exists.
That is to say, the returned value of erase is the first element after the deleted element is returned. According to my code, I ++ again under the first element after the deleted element, the element is skipped, and the natural result is not what I want.
So I modify the code again as follows:
myVec.clear(); cout<<"push_back VEC again"<<endl; for (int i = 0; i <10; i++) { myVec.push_back(i); } printVec(myVec); cout<<"erase VEC in right way"<<endl; for (itePre = myVec.begin(); itePre != myVec.end();) { itePre = myVec.erase(itePre); } printVec(myVec);
The following result is displayed: