Elegant way to find closest value in a vector from above

For reminder:

  • std::lower_bound: returns the first value that does not compare less
  • std::upper_bound: returns the first value that compares strictly greater

From your description, std::lower_bound already looks like the perfect fit, what is wrong with:

int closest(std::vector<int> const& vec, int value) {
    auto const it = std::lower_bound(vec.begin(), vec.end(), value);
    if (it == vec.end()) { return -1; }

    return *it;
}

Which is used as:

int main() {
    std::vector<int> vec;
    vec.push_back(2);
    vec.push_back(4);

    std::cout << closest(vec, 2) << "\n";
    std::cout << closest(vec, 3) << "\n";
    std::cout << closest(vec, 4) << "\n";
}

Output:

2
4
4

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)