c++ - 使用大括号而不是 make_pair 会出现错误

标签 c++ stl lower-bound

它给出没有重载函数“lower_bound”的实例与参数列表匹配错误。我不理解这种行为,因为大括号在配对时通常工作得很好。

使用大括号:

vector<pair<int, int>> a;
auto ptr = lower_bound(a.begin(), a.end(), {2, 3});

使用配对:

vector<pair<int, int>> a;
auto ptr = lower_bound(a.begin(), a.end(), make_pair(2, 3));

最佳答案

编译器无法推导出{2, 3}std::pair<int, int>在此背景下。参见 lower_bound 的声明:

template< class ForwardIt, class T >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value );

编译器不能假设 T应等于 decltype(*first) ,因为情况不一定如此 - 只需要它们具有可比性即可。

您需要通过实际命名您想要使用的类型来消除歧义 - 或者通过调用 std::make_pair(2, 3)或通过创建临时:std::pair{2, 3} (从 C++17 开始可以省略模板参数,对于早期标准,您需要 std::pair<int, int>{2, 3}make_pair )。

关于c++ - 使用大括号而不是 make_pair 会出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69417112/

相关文章:

c++ - std::vector pop_back() 实现

c++ - 用于 std::list 指针排序算法的 STL 谓词

c++ - 使用带有比较结构的 lower_bound 将对象插入到 vector 中

traveling-salesman - 计算旅行推销员(TSP)的持有卡普下限

java - Java 库是否具有 C++ 中的 std::lower_bound() 、 std::upper_bound() 之类的函数?

c++ - 忽略了 OpenMP 任务依赖性?

c++ - c++ 中基于范围的 for 循环的替代方法

c++ - 模板化 c++ 类的 cython 包装给出 undefined symbol

c++ - 如何将 vector<char*> 转换为 vector<string>/string

c++ - 如何加快从文件流中加载 15M 整数?