Skip to content

Instantly share code, notes, and snippets.

@tallytalwar
Last active September 25, 2016 01:20
Show Gist options
  • Save tallytalwar/2444e9dd311ec16a00b8 to your computer and use it in GitHub Desktop.
Save tallytalwar/2444e9dd311ec16a00b8 to your computer and use it in GitHub Desktop.
Fast std::vector removal when order is not a priority
#include <iostream>
#include <memory>
#include <vector>
#include <chrono>
#include <ctime>
#include <algorithm>
struct Foo
{
int i;
std::string str;
Foo(int _i, std::string _str) : i(_i), str(_str) {}
Foo(Foo&& _other) : i(std::move(_other.i)), str(std::move(_other.str)) {}
Foo operator=(Foo&& _other) {
i = std::move(_other.i);
str = std::move(_other.str);
return std::move(*this);
}
};
int main() {
std::vector<Foo> vec1;
std::vector<Foo> vec2;
for(int i = 0; i < 2000; i++) {
vec1.push_back(Foo(i%500, "blah"));
vec2.push_back(Foo(i%500, "blah"));
}
auto start = std::clock();
for(auto itr = vec1.begin(); itr != vec1.end(); ) {
if(itr->i == 400) {
//std::cout<<itr->i<<"\n";
*itr = std::move(vec1[vec1.size()-1]);
//std::cout<<itr->i<<"\n";
vec1.pop_back();
}
itr++;
}
auto end = std::clock();
for(auto itr = vec2.begin(); itr != vec2.end(); ) {
if(itr->i == 400) {
itr = vec2.erase(itr);
} else {
itr++;
}
}
auto finish = std::clock();
std::cout<<"sizeof vec1: "<<vec1.size()<<"\ttime used: "<<1000.0 * (end - start) / CLOCKS_PER_SEC<<"\n";
std::cout<<"sizeof vec2: "<<vec2.size()<<"\ttime used: "<<1000.0 * (finish - end) / CLOCKS_PER_SEC;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment