I am developing a big code base and wanted to use set-s from the STL to store double elements. I just ran some tests and found something very weird.
Here's my source code
#include <iostream>
#include <set>
#include <numeric>
#include <algorithm>
int main()
{
double iter = 0.001;
int count = 0;
std::set<double> S;
while(count < 10)
{
S.insert(iter);
std::cout << "Inserted element is " << iter << std::endl;
iter += 0.001;
count++;
}
for (std::set<double>::iterator i = S.begin(); i != S.end(); i++)
{
double element = *i;
std::cout << "The element in the set is " << element << std::endl;
}
std::cout << "The count of the element to be found is " << S.count(0.009) << std::endl;
if (S.find(0.008) != S.end())
std::cout << "set::find found it!" << std::endl;
else
std::cout << "set::find didn't find it!" << std::endl;
if (std::find(S.begin(), S.end(), 0.009) != S.end())
std::cout << "std::find found it!" << std::endl;
else
std::cout << "std::find didn't find it!" << std::endl;
return 0;
}
Now, the weird part is that both set::find
and std::find
are able to find all elements until 0.008
but cannot find anything after that.
The output I get for the above code is shown below:
Inserted element is 0.001
Inserted element is 0.002
Inserted element is 0.003
Inserted element is 0.004
Inserted element is 0.005
Inserted element is 0.006
Inserted element is 0.007
Inserted element is 0.008
Inserted element is 0.009
Inserted element is 0.01
The element in the set is 0.001
The element in the set is 0.002
The element in the set is 0.003
The element in the set is 0.004
The element in the set is 0.005
The element in the set is 0.006
The element in the set is 0.007
The element in the set is 0.008
The element in the set is 0.009
The element in the set is 0.01
The count of the element to be found is 0
set::find found it!
std::find didn't find it!
Notice that I have asked set::find
to find 0.008
while I have asked both count
and std::find
to count and find 0.009
respectively. I just wanted to know why I'm seeing such an anomaly.
It is also worth mentioning that both the find
functions have absolutely no problems finding integer elements. I was wondering if this is a double
issue. Even if that's the case, I'm not sure why it is able to find a few elements but not all.
I'm not sure what causes this error but if it's of any use I work on Mac OS X 10.10.3 with gcc 4.9.2.