代码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&lt; _Tp,_Alloc&gt; :: 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;
}
答案 0 :(得分:8)
问题是rend
方法有两种形式:
reverse_iterator rend();
const_reverse_iterator rend() const;
在进行比较时,似乎第一个被使用(虽然我不知道为什么),并且没有定义用于比较'const'和'non-const'迭代器的运算符!=
。但是,在分配给变量时,编译器可以推断出要调用的正确函数,并且一切正常。
答案 1 :(得分:2)
在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的建议有用吗?如果您将!=
替换为==
怎么办? (我知道它会导致运行时错误,但我很好奇编译器对此的响应。)
答案 2 :(得分:-1)
尝试交换!=的操作数,如下所示:
for(rcit = v.rbegin(); v.rend() != rcit; ++rcit)