反向迭代器错误:与“rcit != std::vector<_Tp, _Alloc>::rend() 中的 'oper

reverse iterator error : no match for 'operator!=' in 'rcit != std::vector<_Tp, _Alloc>::rend() with _Tp = int, _Alloc = std::allocator'

本文关键字:Alloc Tp rend oper 中的 rcit 迭代器 vector std 错误      更新时间:2023-10-16

CODE A:

vector< int >::const_reverse_iterator rcit;
vector< int >::const_reverse_iterator tit=v.rend();
for(rcit = v.rbegin(); rcit != tit; ++rcit)
cout << *rcit << " ";

代码 B:

vector< int >::const_reverse_iterator rcit;
for(rcit = v.rbegin(); rcit != v.rend(); ++rcit)
cout << *rcit << " ";

代码 A 工作正常,但为什么代码 B 通过错误:

DEV C++\vector_test.cpp 在 'rcit != std::

vector<_Tp, _Alloc>::rend() 中与 _Tp = int, _Alloc = std::allocator' 中的 'operator!=' 不匹配

这就是我试图编写的程序。

#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using namespace std;
#include <vector>
using std::vector;
template< typename T > void printVector( const vector< T > &v);
template< typename T > 
void printVector( const vector< T > &v)
{
             typename vector< T >::const_iterator cit;
             for(cit = v.begin(); cit != v.end(); ++cit)
             cout << *cit << " ";
}
int main()
{
    int number;
    vector< int > v;
    cout << "Initial size of the vector : " << v.size()
         << " and capacity : " << v.capacity() << endl;
    for(int i=0; i < 3; i++)
    {
            cout << "Enter number : ";
            cin >> number;
            v.push_back(number);
    }
    cout << "Now size of the vector : " << v.size()
         << "and capacity : " << v.capacity() << endl;
    cout << "output vector using iterator notation " << endl; 
    printVector(v);
    cout << "Reverse of output ";
    vector< int >::const_reverse_iterator rcit;
    for(rcit = v.rbegin(); v.rend() != rcit ; ++rcit)
    cout << *rcit << " ";
    cin.ignore(numeric_limits< streamsize >::max(), 'n'); 
    cin.get();
return 0;
}

问题是rend方法有两种形式:

reverse_iterator rend();
const_reverse_iterator rend() const;

在进行比较时,似乎使用了第一个(尽管我不知道为什么),并且没有定义用于比较"const"和"non-const"迭代器的运算符!=。但是,当分配给变量时,编译器可以推断出要调用的正确函数,并且一切都可以正常工作。

当我在 Xcode 4 或代码板中编译以下内容时,我没有收到任何错误或警告:

#include <iostream>
#include <vector>
int main () {
    using namespace std;
    vector< int > v;
    vector< int >::const_reverse_iterator rcit;
    for(rcit = v.rbegin(); rcit != v.rend(); ++rcit)
        cout << *rcit << " ";
}

您的程序与此有何重大不同?您使用什么编译器?奥格尼安的建议有效吗?如果你用==替换!=怎么办?(我知道这会导致运行时错误,但我很好奇编译器对此的反应。

尝试像这样交换 != 的操作数:

for(rcit = v.rbegin(); v.rend() != rcit; ++rcit)