反向迭代器允许您重用通用代码,因为您可以像对待普通迭代器一样对待它们,调用++ 进行反向操作。例如:
#include <iostream>
#include <string>
template <class Iterator>
void printAll(Iterator begin, Iterator end)
{
for (auto it = begin; it != end; ++it) // ++ can mean "go backwards"
// if Iterator is a reverse
// iterator
{
std::cout << *it << "\n";
}
}
int main()
{
std::string s = "123";
printAll(s.begin(), s.end()); // prints 1, 2, 3
printAll(s.rbegin(), s.rend()); // prints 3, 2, 1
}
请注意,您无需使用 -- 为 printAll 编写反向版本。
现在,考虑<algorithm> 中的所有函数。反向迭代器的存在意味着您可以轻松地以反向方式使用它们。比如有std::copy_n,但没有std::reverse_copy_n,但是有了反向迭代器,就没有必要了,因为你可以这样写:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
std::string input = "abcdef";
std::string output;
std::string output_reversed;
// copy the first 3 elements:
std::copy_n(input.begin(), 3, std::back_inserter(output));
// copy the first 3 elements going backwards, starting at the last one:
std::copy_n(input.rbegin(), 3, std::back_inserter(output_reversed));
std::cout << output << "\n"; // prints abc
std::cout << output_reversed << "\n"; // prints fed
}
对于非通用代码,例如在您的问题中,这更像是一个样式问题,很少有技术上合理的论据来选择一个而不是另一个。