为了简化我的问题,我将使用std::string::iterator和std::string::reverse_iterator,但问题一般是关于迭代器的。
是否有特殊原因使用以下循环向后迭代:
std::string s = "something";
for (std::string::reverse_iterator it = s.rbegin(); it != s.rend(); ++it)而不是这个:
std::string s = "something";
std::string::iterator it = in.end();
while(it!=in.begin())
{
it--;
//do something
}发布于 2016-11-19 10:17:17
反向迭代器允许您重用泛型代码,因为您可以像对待普通迭代器一样对待它们,并调用++进行倒退。例如:
#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
}对于非泛型代码,比如在您的问题中,这更像是一个样式问题,很少有技术上合理的参数来选择一个而不是另一个。
发布于 2016-11-19 09:20:44
因为begin()指向第一个成员,end()指向最后一个成员,这就是干净的代码(因为如果不使用反向迭代器,那么首先执行迭代器减量,然后执行,然后将迭代器与begin()进行比较,但这是错误的,因为begin()之后的指向现有的第一个元素。
向量::end() at cplusplus.com
https://stackoverflow.com/questions/40691100
复制相似问题