What is the most efficient and fastest way to compare elements in a vector of class using two iterators? The vector is not a sortable one and I have an overloaded ">" operator for the class. I use boost foreach for simple vector iterations.
I am doing something similar to the one given below.
vector<TestClass*> vec;
vector<TestClass*>::iterator jIter;
bool isErased=false;
vector<TestClass*>::iterator iIter = vec.begin();
if(!vec.empty()){
while(iIter < vec.end()-1) {
isErased = false;
for (jIter = iIter+1; jIter < vec.end();jIter++) {
if((*(*iIter))<=(*(*jIter))) {
delete *jIter;
jIter = vec.erase(jIter);
jIter--;
}
else if((*(*iIter))>=(*(*jIter))) {
delete *iIter;
iIter = vec.erase(iIter);
isErased = true;
break;
}
}
if(!isErased) iIter++;
}
Thank you.
The most tricky part is to avoid running into invalidated iterators:
v.erase(std::remove_if(v.begin(), v.end(), [j](T const &i) { return i > j; });
You could also employ a loop, but use reverse iterators in that case
PS: I can't grok what you actually wanted achieve in your algorithm
You might be interested in
Untested but something like this.
for(auto it=vec.begin(), end=vec.end(); it!=end; ++it) {
const auto&& val=*it;
std::size_t count=0u;
end=std::remove_if(
it, end,
[&](const TestClass& tc) -> bool {
if(tc==val) ++count;
return (count > 1);
}
);
}
vec.erase(end, vec.end());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.