Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

finding the closest or equal numer in a vector.



  • 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;
    

  • Moderators

    @Natural_Bugger
    there's
    std::lower_bound and std::upper_bound

    but in your case, of an unordered container those may not return the absolute closest match

    actually
    std::nth_element

    could be what you're looking for :D



  • @JonB

    thnx for your help.
    when i sorted the vector, it worked, mine aswel yours.

    how hard can it be
    : )


Log in to reply