So, think that we have two vectors, vec1 and vec2. What would be the fastest way to only perform some operation to elements, which are in both vectors. This far, I have made this. Simply, how can we achieve this faster, or is there any way:
vector<Test*> vec1;
vector<Test*> vec2;
//Fill both of the vectors, with vec1 containing all existing
//objects of Test, and vec2 containing some of them.
for (Test* test : vec1){
//Check if test is in vec2
if (std::find(vec2.begin(), vec2.end(), test) != vec2.end){
//Do some stuff
}
}
Your approach is O(M*N) because it calls std::find
linear in the number of elements of vec2
for each element of vec1
. You can improve upon it in several ways:
vec2
would let you reduce the time to O((N+M)*Log M) - i.e. you can use binary search on the range vec2.begin(), vec2.end()
vec2
element would let you reduce the time to O(N+M) - now both the construction time of the set and the search in it are linear.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With