C++ 标准容器附带了称为“反向迭代器”的东西。使用std::vector::rbegin()
and std::vector::rend()
获得一个向后迭代向量的迭代器。 C++03 可以轻松做到这一点:
#include <iostream>
#include <vector>
// Use const reference to pass expensive-to-copy types
void loop_body(const int& i)
{
std::cout << i;
}
int main( int argc, char** )
{
// pretend this is a vector of expensive objects
std::vector<int> foo = {1,2,3,4,5};
// calculate forward or backward iteration direction
bool backwards = (argc > 1);
if( backwards ) {
std::for_each(foo.rbegin(), foo.rend(), &loop_body);
} else {
std::for_each(foo.begin(), foo.end(), &loop_body);
}
return 0;
}
您可以使用 C++11 中的 lambda 来做到这一点:
#include <iostream>
#include <vector>
int main( int argc, char** )
{
// pretend this is a vector of expensive objects
std::vector<int> foo = {1,2,3,4,5};
// calculate forward or backward iteration direction
bool backwards = (argc > 1);
// Use const reference to pass expensive-to-copy types
auto loop_body = [](const int& i)
{
std::cout << i;
};
if( backwards ) {
std::for_each(foo.rbegin(), foo.rend(), loop_body);
} else {
std::for_each(foo.begin(), foo.end(), loop_body);
}
return 0;
}