繁体   English   中英

反向迭代器错误:'rcit!= std :: vector <_Tp,_Alloc> :: rend()中的'operator!='与_Tp = int,_Alloc = std :: allocator'不匹配

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

代码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 << " ";

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

DEV C ++ \\ vector_test.cpp 与'rcit!= std :: vector <_Tp,_Alloc> :: rend()中的'operator!='匹配_Tp = int,_Alloc = std :: allocator'

这是我试图编写的程序。

#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或codepad中编译以下内容时,我没有收到任何错误或警告:

#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 << " ";
}

您的计划是否以任何重要方式与此不同? 你用的是什么编译器? ognian的建议有用吗? 如果你用==替换!=怎么办? (我知道它会导致运行时错误,但我很好奇编译器对此的响应。)

尝试交换!=的操作数,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM