finding the closest or equal numer in a vector.
Solved
C++ Gurus
-
hello,
i'm looking for a value that is closest but smaller or equal to b.
the vector contains random numbers smaller or bigger than b.this method doesn't cut the mostard, somehow
vector<int> temp; int tempNum = 0; for(auto ii : temp){ if(ii <= b){ //printf("Integer value is %d\n" , ii); tempNum = ii; } }
-
@Natural_Bugger
Well, it doesn't "cut the mostard, somehow" because you seem to check whether something is smaller each time but not whether it's closer than the current best guess.It doesn't help that your code uses unhelpful variable names and doesn't declare/initialize them all!
You will want something like:
int target = <whatever the target is>; int closestLessThanOrEqualTo; bool foundAnyClosest = false; for (auto num : vector) if (num <= target) if (!foundAnyClosest) { closestLessThanOrEqualTo = num; foundAnyClosest = true; } else if (num > closestLessThanOrEqualTo) closestLessThanOrEqualTo = num;
-
@Natural_Bugger
there's
std::lower_bound and std::upper_boundbut in your case, of an unordered container those may not return the absolute closest match
actually
std::nth_elementcould be what you're looking for :D