vector<int> :: iterator itr1;
cin >> query;
for(i = 0; i < query ; i++)
{
cin >> checknum;
if (binary_search (v.begin(), v.end(), checknum))
{
itr1 = lower_bound(v.begin(), v.end(), checknum);
cout << "Yes " << itr1 << endl;
}
else
{
itr1 = lower_bound(v.begin(), v.end(), checknum);
cout << "No " << itr1 << endl;
}
}
我在编译期间遇到错误:编译消息
solution.cc: In function 'int main()':
solution.cc:28:18: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
cout << "Yes " << itr1 << endl;
^
In file included from /usr/include/c++/4.9/iostream:39:0,
from solution.cc:4:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]'
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
^
solution.cc:33:18: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
cout << "No " << itr1 << endl;
^
In file included from /usr/include/c++/4.9/iostream:39:0,
from solution.cc:4:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]'
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
答案 0 :(得分:1)
std::lower_bound
返回std::vector<int>::iterator
,您无法使用cout
进行打印。
可能你的意思是:
cout << "Yes " << *itr1 << endl;
cout << "No " << *itr1 << endl;
答案 1 :(得分:0)
迭代器无法传递给std::cout
。
要获得正确的位置,我们需要从v.begin()
中减去itr1
,
即:
cout << distance(v.begin(), itr1) << endl;
答案 2 :(得分:0)
如果你想打印位置,你应该做这样的事情。
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20);
up= std::upper_bound (v.begin(), v.end(), 20);
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
我希望它有所帮助。