srk*_*ing 3 c++ iteration c++11
我有一个大型对象的容器,复制起来很昂贵.我有时必须正常地迭代整个容器,有时反过来.一旦我确定了迭代方向,我就不需要改变飞行中途,即不需要随机访问.
我希望做这样的模式:
#include <iostream>
#include <vector>
using namespace std;
int main( int argc, char** )
{
// pretend this is a vector of expensive objects
vector<int> foo = {1,2,3,4,5};
// calculate forward or backward iteration direction
bool backwards = (argc > 1);
if( backwards )
// prepare backward iteration, but don't copy objects
else
// prepare forward iteration, but don't copy objects
for( auto& i : /* either forward or backward */ )
{
// my loop body
cout << i;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是一个C++ 11程序,但我不认为这对我有帮助.我只是没有看到最好的方法来做到这一点.谢谢你的帮助.
C++标准容器带有这些称为"反向迭代器"的东西.使用std::vector::rbegin()
和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;
}
Run Code Online (Sandbox Code Playgroud)
你可以在C++ 11中使用lambdas来做到这一点:
#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;
}
Run Code Online (Sandbox Code Playgroud)
你为什么不把你的算法放到模板函数中?然后用begin/end或rbegin/rend调用它是微不足道的.
template <class Iterator>
void do_stuff(Iterator first, Iterator last)
{
// Your loop code here.
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用lambda(因为它是C++ 11)以及std::for_each
:
auto loop_body = [&](int &i) { std::cout << i << std::endl; } ;
if (backward)
std::for_each(v.rbegin(), v.rend(), loop_body);
else
std::for_each(v.begin(), v.end(), loop_body);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1565 次 |
最近记录: |