这取决于迭代器是如何定义的。
似乎对于类模板std::array,迭代器被定义为一个指针。所以功能开始,结束。 cbegin, cend 只返回指针。因此,当指针按值返回时,您可能不会减少它,因为需要 lvalue..
对于类模板std::vector,迭代器被定义为一个用户定义的类,为其定义了操作符--()。
考虑以下演示程序
#include <iostream>
class Int
{
public:
Int( int x = 0 ) : x ( x )
{
}
Int & operator --()
{
--x;
return *this;
}
friend std::ostream & operator <<( std::ostream &os, const Int &i )
{
return os << i.x;
}
private:
int x;
};
int f( int x )
{
return x;
}
Int f( Int x )
{
return x;
}
int main()
{
std::cout << --f( Int( 10 ) ) << std::endl;
// error: lvalue required as decrement operand
// std::cout << --f( 10 ) << std::endl;
return 0;
}
考虑到你会写
auto arrIt = std::prev( arr.end() );
而不是
auto arrIt = --arr.end();
前提是您包含标题<iterator>。
您可以将运算符与类模板 std::array 的反向迭代器一起使用,因为标准明确定义了它们
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
而用户定义的类std::reverse_iterator 定义了operator --()。
这是一个演示程序
#include <iostream>
#include <array>
int main()
{
std::array<double, 2> arr = { { 1, 2 } };
auto it = --arr.rend();
std::cout << *it << std::endl;
return 0;
}