Uploaded image for project: 'C++ Standard Library'
  1. C++ Standard Library
  2. STDCXX-1033

incorrect documentation of nth_element in User's Guide

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • 4.2.1
    • 4.2.2
    • Documentation
    • None
    • Incorrect Behavior

    Description

      From an external source:

      There appears to be an error in your documentation here:

      http://stdcxx.apache.org/doc/stdlibug/14-3.html#idx353

      This is your example:

      The example program illustrates finding the fifth largest value in a vector of random numbers.

      void nth_element_example()
      // illustrates the use of the nth_element algorithm
      // see alg7.cpp for complete source code
      {
        // make a vector of random integers
        std::vector<int> aVec(10);
        std::generate(aVec.begin(), aVec.end(), randomValue);
       
        // now find the 5th largest
        std::vector<int>::iterator nth = aVec.begin() + 4;
        std::nth_element(aVec.begin(), nth, aVec.end());
       
        std::cout << "fifth largest is " << *nth << std::endl;
      }
      

      However nth_element uses < as the default predicate so your example will produce the 5th smallest element, not the 5th largest.

      To get the fifth largest you should use std::greater<int>() as a predicate or use the fifth from the other end, i.e. aVec.end() - 5.

      Attachments

        Activity

          People

            sebor Martin Sebor
            sebor Martin Sebor
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Time Tracking

                Estimated:
                Original Estimate - 1h
                1h
                Remaining:
                Time Spent - 0.5h Remaining Estimate - 0.5h
                0.5h
                Logged:
                Time Spent - 0.5h Remaining Estimate - 0.5h
                0.5h