开发者

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

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

CODE B:

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

CODE A works fine but why does CODE B throughs error :

DEV C++\vector_test.cpp no match for 'operator!=' in 'rcit != std::vector<_Tp, _Alloc>::rend() with _Tp = int, _Alloc = std::allocator'.

This is the program I was trying to write.

#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(开发者_JS百科), '\n'); 
    cin.get();
return 0;
}


The problem is there are two forms of the rend method:

reverse_iterator rend();
const_reverse_iterator rend() const;

When doing the comparison it seems the first is being used (though I don't know why), and the operator != for comparing a 'const' and a 'non-const' iterator is not defined. When assigning to the variable though, the compiler can deduce the correct function to call and it all works correctly.


I don't get any errors or warnings when I compile the following in Xcode 4 or 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 << " ";
}

Does your program differ from this in any significant way? What compiler are you using? Does ognian's suggestion work? And what if you replace the != with an ==? (I know it would cause a run-time error but I curious about the compiler's response to this.)


Try swapping the operands of != like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜