Last active
September 25, 2016 01:20
-
-
Save tallytalwar/2444e9dd311ec16a00b8 to your computer and use it in GitHub Desktop.
Fast std::vector removal when order is not a priority
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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