矢量上的错误

Error On vector

本文关键字:错误      更新时间:2023-10-16
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)

std::lower_bound返回一个std::vector<int>::iterator,你不能使用cout打印它。

可能你的意思是:

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

如果你想打印位置,你应该做这样的事情。

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';

我希望它有所帮助。

迭代器不能传递给std::cout

为了得到正确的位置,我们需要从itr1中减去v.begin(),即:

cout << distance(v.begin(), itr1) << endl;