反向迭代器错误:与“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'
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)
相关文章:
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- 组件对象模型 (COM):IMalloc::Alloc 在哪里分配内存?
- 获取错误:在抛出"std::bad::alloc"的实例后终止调用 what(): std::bad_alloc
- 线程池的计时测试:单线程 vs 回调 tp vs 未来 tp
- CGAL:Hausdorff距离不良Alloc
- C STD ::初始化类对象中的Alloc错误错误
- 尝试解决HackerBank上的BFS挑战时出现错误的alloc异常
- 从 BSTR tp std::string 转换大字符串
- 为背包算法使用向量时抛出了错误的alloc
- 错误 C2228:'.Alloc'左侧必须具有类/结构/联合
- 为什么 cocos2d 和 libdispatch.dylib 如此频繁地调用 alloc
- 在分配器中使用new函数和*alloc函数时,它们之间有区别吗
- 为什么'has_construct<Alloc, T, Args...>::value'在gcc(false)和clang(true)上给出不同的值?
- 如何追踪"tcmalloc : large alloc .... "
- c++中的Alloc数组,c#中的free数组
- Cppcheck认为在alloc和dealloc中存在不匹配
- C++Alloc错误将对象添加到OpenMPI For循环中的矢量(或Deque或List)
- 一个快速的new/delete和alloc/free