一:功能
用于查找元素,它返回了 lower_bound, upper_bound 这两个函数查找结果值。
1. lower_bound 是返回第一个大于等于查找元素的位置。
2. upper_bound 是返回第一个大于查找元素的位置
二:用法
#include <vector>
#include <algorithm>
#include <iostream>int main() {std::vector<int> data{1, 2, 3, 4, 5, 6, 6, 6, 7, 8, 9};auto [lb, ub] = std::equal_range(data.begin(), data.end(), 6);std::cout << "*lb == " << *lb << "\n"; //6std::cout << "*ub == " << *ub << "\n"; //7
}
#include <algorithm>
#include <complex>
#include <iostream>
#include <vector>struct S
{int number;char name;// note: name is ignored by this comparison operatorbool operator<(const S& s) const { return number < s.number; }
};struct Comp
{bool operator()(const S& s, int i) const { return s.number < i; }bool operator()(int i, const S& s) const { return i < s.number; }
};int main()
{// note: not ordered, only partitioned w.r.t. S defined belowconst std::vector<S> vec{{1, 'A'}, {2, 'B'}, {2, 'C'},{2, 'D'}, {4, 'G'}, {3, 'F'}};const S value{2, '?'};std::cout << "Compare using S::operator<(): ";const auto p = std::equal_range(vec.begin(), vec.end(), value);for (auto it = p.first; it != p.second; ++it)std::cout << it->name << ' ';std::cout << '\n';std::cout << "Using heterogeneous comparison: ";const auto p2 = std::equal_range(vec.begin(), vec.end(), 2, Comp{});for (auto it = p2.first; it != p2.second; ++it)std::cout << it->name << ' ';std::cout << '\n';using CD = std::complex<double>;std::vector<CD> nums{{1, 0}, {2, 2}, {2, 1}, {3, 0}, {3, 1}};auto cmpz = [](CD x, CD y) { return x.real() < y.real(); };#ifdef __cpp_lib_algorithm_default_value_typeauto p3 = std::equal_range(nums.cbegin(), nums.cend(), {2, 0}, cmpz);#elseauto p3 = std::equal_range(nums.cbegin(), nums.cend(), CD{2, 0}, cmpz);#endiffor (auto it = p3.first; it != p3.second; ++it)std::cout << *it << ' ';std::cout << '\n';
}