Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved finding the closest or equal numer in a vector.

    C++ Gurus
    3
    4
    341
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • N
      Natural_Bugger last edited by Natural_Bugger

      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;
              }
          }
      
      JonB J.Hilk 2 Replies Last reply Reply Quote 0
      • JonB
        JonB @Natural_Bugger last edited by JonB

        @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;
        
        N 1 Reply Last reply Reply Quote 0
        • J.Hilk
          J.Hilk Moderators @Natural_Bugger last edited by J.Hilk

          @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

          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct

          Qt Needs YOUR vote: https://bugreports.qt.io/browse/QTQAINFRA-4121


          Q: What's that?
          A: It's blue light.
          Q: What does it do?
          A: It turns blue.

          1 Reply Last reply Reply Quote 0
          • N
            Natural_Bugger @JonB last edited by

            @JonB

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

            how hard can it be
            : )

            1 Reply Last reply Reply Quote 0
            • First post
              Last post