Probably doing something wrong? Trying to use binary search to delete an instance from a class from an array. Instances are added to an array when created, but when I delete them from the scene I want them to be deleted from the array too. Somehow binary_search is working fine with the first delete, but not when deleting a second instance.
binary_search should return true if an instance is found in the array. But it returns false, when the instance is definitely present in the array.
Here is the code I am using.
void Manager::eraseInstance(SomeInstance* instance) {
cout<< " found?: " << binary_search(instanceArray.begin(), instanceArray.end(), instance) << " instance: " << instance;
for (int i = 0; i < instanceArray.size(); i++) {
cout << " " << i << ": " << instanceArray[i];
}
cout << endl;
if (binary_search(instanceArray.begin(), instanceArray.end(), instance)) {
for (int i = 0; i < instanceArray.size(); i++) {
if (instanceArray[i] == instance) {
instanceArray.erase(instanceArray.begin() + (i));
delete instance;
}
}
}
}
For debugging I first cout the search result, then the instance I try to erase, and then all instances present in the array.
Now my output in the console is the following:
Deleting the first instance output:
found?: 1 instance: 05DCB358 0: 05DCAED8 1: 05DCB358 2: 05DCADB8
Ok so everything is going well there, the instance is found, the instance identifier is the same as the second instance in the array. And everything is working fine.
Deleting the second instance output:
found?: 0 instance: 05DCADB8 0: 05DCAED8 1: 05DCADB8
So the next instance I try to delete, this happens. The binary search cannot find the instance (BUT as you can see it is still present in the array as the second instance of the array). Because it returns false the instance is not deleted, even though my output confirms the instance is present, but binary_search says it is not?
Anyone know what is happening here?
std::lower_boundinstead ofstd::binary_search, since you can get the iterator to the actual found element back, rather than following up with a linear search.binary_searchrequires the collection to be sorted, which doesn't seem to be true in your case, or am I missing something?binary_searchreturns true is killing any benefit you get from using a binary search.std::lower_boundgives you the location of a matching element if there is one.std::binary_searchjust tells you whether a particular element is present.