I've a std::vector<int> and I need to remove all elements at given indexes (the vector usually has high dimensionality). I would like to know, which is the most efficient way to do such an operation having in mind that the order of the original vector should be preserved.
Although, I found related posts on this issue, some of them needed to remove one single element or multiple elements where the remove-erase idiom seemed to be a good solution. In my case, however, I need to delete multiple elements and since I'm using indexes instead of direct values, the remove-erase idiom can't be applied, right? My code is given below and I would like to know if it's possible to do better than that in terms of efficiency?
bool find_element(const vector<int> & vMyVect, int nElem){ return (std::find(vMyVect.begin(), vMyVect.end(), nElem)!=vMyVect.end()) ? true : false; } void remove_elements(){ srand ( time(NULL) ); int nSize = 20; std::vector<int> vMyValues; for(int i = 0; i < nSize; ++i){ vMyValues.push_back(i); } int nRandIdx; std::vector<int> vMyIndexes; for(int i = 0; i < 6; ++i){ nRandIdx = rand() % nSize; vMyIndexes.push_back(nRandIdx); } std::vector<int> vMyResult; for(int i=0; i < (int)vMyValues.size(); i++){ if(!find_element(vMyIndexes,i)){ vMyResult.push_back(vMyValues[i]); } } }
vec.begin() + index).elementthat is at a givenposition. In my code, anelementis represented byvMyValuesand thepositionby thevMyIndexes.std::vector---sdt::list(linked-list container) orstd::set(container where the key is the values themselves)