using erase with remove_if

若如初见. 提交于 2021-02-17 04:53:09

问题


This thing drive me crazy, I couldn't understand it :

// v contains : 101, 1, 2, 3, 4 , 5
v.erase(remove_if(v.begin(), v.end(), bind2nd(less<int>(), 3)), v.end());
// v contains now : 101, 3, 4, 5

Why there is v.end() as a second argument in erase ?? I read that remove_if returns an iterator to the element that follows the last element not removed, what does it mean.... v.erase(v.begin(), v.end()) should erase all the vector elements, but how in the example above it does not erase 3, 4 and 5 ? how this thing works ? I didn't find something edifiying about it in the internet.


回答1:


remove doesn't actually remove any elements in the vector but it moves them to the end of the vector. It then returns an iterator to the new last element which is the first "removed" element. You then erase from that iterator to the end of the vector to actually get rid of the elements in the vector.



来源:https://stackoverflow.com/questions/33027202/using-erase-with-remove-if

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!