c++nth-element

std::nth_element provides wrong value


From a given unsorted vector I want to get the nth smallest element. I figured out that there is a method in the standard library. But I do not understand the following result.

I took the vector with entries {3,4,5,2,3} and want to have the 2th smallest element. If I execute the following code, I get the number 2 at the second position, actually it should be the 3. Because 2 is the 1st smallest element and not the second.

What is my mistake?

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
  std::vector<size_t> temp;
  temp.assign({3,4,5,2,3});
  std::nth_element (temp.begin(), temp.begin()+2, temp.end());
  std::cout << std::endl;
  for(size_t i=0;i<temp.size();i++){ printf("%.2f\n",(double)temp[i]);  }
}

Solution

  • temp.begin()+2 gives you the third element of the vector, not the second. The first element is temp.begin() (i.e. temp.begin() + 0), and the second element is temp.begin() + 1. So you want to do this:

    std::nth_element (temp.begin(), temp.begin()+1, temp.end());