I have a vector afor storing values [0 1 2 3 5]and another vector removelistfor storing indexes that need to be removed [0 1 2]to be left [3 5]at the end. When I implement the following code, it will delete the elements unexpectedly, as the vector awill reorder during the process. Is there a way to achieve my goal?
a
[0 1 2 3 5]
removelist
[0 1 2]
[3 5]
for (int i = 0; i<removelist.size() ; i++) a.erase(a.begin() + removelist[i]);
Cancel the order of deleting values, i.e. use reverse iterators removelist. This, of course, depends on the sorting removelist.
Maybe something like
std::sort(removelist.begin(), removelist.end()); // Make sure the container is sorted for (auto &i = removelist.rbegin(); i != removelist.rend(); ++ i) { a.erase(a.begin() + *i); }
, remove_if:
remove_if
auto& rm = removelist; // for brevity a.erase(remove_if(begin(a), end(a), [&](int i) { auto idx = distance(begin(v), find(begin(v), end(v), i)); return find(begin(rm), end(rm), idx) != end(rm); }, end(a));
- , , :
// pseudocode: vector tmp; tmp.reserve(a.size() - removelist.size()); for (i=0; i<a.size(); ++i) { if (i not in removelist) { tmp.push_back(a[i]); } } a.swap(tmp);
:
removelst
Source: https://habr.com/ru/post/1626302/More articles:How to give cornerRadius for UIBezierPath - iosAngularJS - Creating a floating scroll down / back to the top button - javascriptUnderstanding BPP Inside DICOM Images - dicomGet all elements with `position: fixed` in an HTML page? - javascriptreplace default application.conf file with spark-submit - apache-sparkangular2 Невозможно разрешить все параметры для 'RequestOptions' (?) - angularMysql sum column according to another column - mysqlThe radio camera does not work in - javascriptLINQ разделяет строку на предложения в зависимости от котировок - c#How to get a hot swap of a webpack module (reaction-hot-loader) that works when proxying your own socket.io server - webpackAll Articles