Using std::lower_bound with std::vector::const_iterator
Using std::lower_bound with std::vector::const_iterator
我试图在向量的下一个迭代器位置到向量末尾的部分找到边界。
代码为:
#include <algorithm>
#include <vector>
#include <iostream>
int
main()
{
typedef std::vector<int> Vector;
Vector v;
v.push_back(3);
v.push_back(7);
v.push_back(15);
v.push_back(21);
std::sort(v.begin(), v.end());
for (Vector::const_iterator i = v.begin(); i != v.end(); ++i) {
Vector::const_iterator low = std::lower_bound(i+1, v.end(), -10-*i);
Vector::const_iterator high = std::upper_bound(i+1, v.end(), 10-*i);
for (Vector::const_iterator j = low; j != high; ++j) {
std::cout << *i << "~" << *j << std::endl;
}
}
return 0;
}
不幸的是,std::lower_bound(i+1, v.end(), -10-*i)
触发了我无法理解的编译错误:
c++ -O3 -ggdb -std=c++11 -W -Wall -pedantic -Wl,-stack_size -Wl,0x1000000 2sum.cc -o 2sum
2sum.cc:26:26: error: no matching function for call to 'lower_bound'
V::const_iterator lo = std::lower_bound(i+1, a.end(), -1...
^~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:4085:1: note:
candidate template ignored: deduced conflicting types for parameter
'_ForwardIterator' ('__wrap_iter<const long *>' vs.
'__wrap_iter<long *>')
lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp...
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:4070:1: note:
candidate function template not viable: requires 4 arguments, but 3 were
provided
lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp...
^
上面的语句有什么问题?如何使用i+1
迭代器正确调用std::lower_bound
?
错误可能表示无法推导模板参数-i
是const_iterator
,而v.end()
返回iterator
。这应该会奏效:
std::lower_bound( i+1, v.cend(), -10-*i);
^^^^^^^^
相关文章:
- cppcheck在const std::string[]上引发警告
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 如何在旧c++中初始化const-std向量
- 使用 std::string () const 函数启动线程或未来
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- r语言 - C++ 类型为"const std ::?
- 将函数参数"const char*"转换为"std::string_view"是
- std::span<const T> 作为函数模板中的参数
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- std::p ackaged_task 应该删除带有 const 参数的复制 c'tor
- std::move a const std::vector in a lambda capture
- std::d ecay 并删除 const 限定符
- C++ TCP 套接字 | 无法将"std::__cxx11::字符串"转换为"const
- 为什么"std::add_pointer"会添加之前删除的"const"?
- 可以使用<size_t>static_const(),std::as_const()或static_cast<const size_t>()来声明数组吗?
- "No suitable conversion function from 'std::string' to 'const char *' exists"
- 使用 std::size 来自非 const 上下文
- 无法从'const std::string [3]'转换为'std::string'
- 从 std::string 转换为 const 无符号整数