Std lib-like C++ function to find nearest elements in a container
I think all you need is std::nth_element:

template&lt;typename Q, typename I, typename Distance&gt;
void find_n_nearest(const Q&amp; q, I first, I nth, I last, Distance dist)
{
    using T = decltype(*first);
    auto compare = [&amp;q, &amp;dist] (T i, T j) { return dist(i, q) &lt; dist(j, q); };
    std::nth_element(first, nth, last, compare);
    std::sort(first, last, compare);
}

int main()
{
    auto distance = [] (int i, int j) { return std::abs(i-j); };
    std::vector&lt;int&gt; v = {56, 10, 79841651, 45, 59, 68, -20, 0, 36, 23, -3256};
    auto res = {0, 10, 23, -20, 36};

    find_n_nearest(4, v.begin(), v.begin() + 5, v.end(), distance);
    assert(std::equal(v.begin(), v.begin() + 5, res.begin()));
}


If you just need the n nearest elements but not necessarily sorted, you can skip std::sort. Then complexity is linear in n.

I have skipped the initial copy part, because it's not always needed. Feel free to add it if you like.