从特定位置调用Upper_bound函数,而不是使用data.begin()
upper_bound function from a specific position instead of data.begin()
我试图从排序对向量中找出第一个大于给定Number
的数字。我用upper_bound
,它工作得很好。代码如下所示:
bool cmp(int n, pair<int, int> const& p)
{
return (p.first > n) ;
}
vector<pair<int,int>> v;
vector<pair<int,int>>::iterator up;
//int Number = ...;
// .......
up = upper_bound(v.begin(), v.end(), Number, cmp);
现在我想从一个特定的位置而不是开始搜索。所以我把代码改成:
up = upper_bound(v.at(i), v.end(), Number, cmp);
,其中i
表示我想从向量v
的ith
位置搜索到end。然而,它给了我一个错误:
error: no matching function for call to 'upper_bound(__gnu_cxx::__alloc_traits<std::
allocator<std::pair<int, int> > >::
value_type&, std::vector<std::pair<int, int> >::iterator, int&,
bool (&)(int, const std::pair<int, int>&))'
是什么原因导致了这样的错误?有没有更好的从给定位置搜索的方法?
std::vector::at
不返回迭代器,这是upper_bound
所需要的。您可以获取到所需位置的迭代器,并像这样传递它:
up = upper_bound(v.begin() + i, v.end(), Number, cmp);
或
up = upper_bound(std::next(v.begin(), i), v.end(), Number, cmp);
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 调用'begin(int [n])'没有匹配函数
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 为constchar*定义std::begin合法吗
- constexpr begin of a std::array
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ 初始化 .data 部分中的变量
- 模式"allocate memory or use existing data"
- boost::asio data owning `ConstBufferSequence`
- remove(str.begin(), str.end(), );无法正常工作(我正在使用视觉工作室 2012)
- Python to C++ Data structure API
- 了解向量中的 .begin 和 .end
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- protobuf C++ SQLite handle blob data
- 混淆 Begin() 方法作为参数
- std::ranges::begin 和 std::begin 有什么区别?
- C++ const char with .begin() and .end()
- 从特定位置调用Upper_bound函数,而不是使用data.begin()