2016-07-05 68 views
-6
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

那么问题是什么?除此之外,你可能想在'cout'语句中使用'* itr1'。 –

+0

您可以将其缩小为2行代码。你发布的大部分内容都是无关紧要的。 – juanchopanza

回答

1

std::lower_bound返回std::vector<int>::iterator,您可以使用cout不能打印。

也许你的意思是:

cout << "Yes " << *itr1 << endl; 
cout << "No " << *itr1 << endl; 
+1

它甚至不管什么'lower_bound'返回。不相干的代码也给你了! – juanchopanza

0

迭代器不能被传递到std::cout

得到适当的位置,我们需要从itr1减去v.begin(), 即:

cout << distance(v.begin(), itr1) << endl; 
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'; 

我希望它有帮助。

+0

为什么投下了票?好。编写'const auto low = std :: lower_bound(v.begin(),v.end(),20)'会更好;'但基本答案是正确的。 –

+0

我有点担心,我能做些什么吗 – dazzieta

+0

是的。请参阅http://meta.stackoverflow.com/a/252271/771073 –