2016-07-05 74 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 –