The problem encountered in the erase element operation of vector in C++ STL.

Today's retest machine test warm-up match.

I wrote a question about topological sorting. I didn't read the algorithm carefully before, so I made up a rough outline of it myself.

Do it with vector.

When using vector's erase operation, "vector iterators incompatible" occurs. I searched the Internet for a long time, but there is no good way.

The code is as follows (just an example)

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	vector<int>::iterator ita = v.begin();
	for(vector<int>::iterator it = v.begin();it!=v.end();){
		if(*it == 2){
			ita = it;
			//it--; add this comment
			v.erase (ita);
			//break;
		}
		else it++;
	}
}

Finally tried it--, it can run normally without error.

After much deliberation, after deleting it, the changed pointer cannot be found, and the subsequent pointer is still based on the pointer, so there will definitely be errors.

And replacing "it--" with "it++" will report the same error.

Such a scenario can be imagined.

A house, three stories high. If the second layer is instantly removed using a certain ability, the third layer will inevitably collapse. The first layer will not be significantly affected (if the third layer falls down...)

After thinking about it, it should be the same principle.

If there is only a single element in the vector that you want to delete, the easiest way is to break directly after deleting it~ to avoid unnecessary trouble~

I fell asleep~ I will continue to brush the questions tomorrow.

ALL KILL!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325516348&siteId=291194637