有没有办法迭代最多N个元素使用基于范围的for循环? [英] Is there a way to iterate over at most N elements using range-based for loop?
问题描述
我想知道如果有一个很好的方法来迭代在容器中的最多N个元素使用基于范围的循环和/或算法从标准库(这是整个点,我知道我可以只使用
基本上,我正在寻找对应于这个Python代码的东西:
for i in arr [:N]:
print(i)
解决方案由于我个人会使用此< a>或此答案(两者均为+1),只是为了增加您的知识 - 您可以使用升压适配器。对于您的情况 - 切片 a>似乎最合适:
#include< boost / range / adapter / sliced.hpp>
#include< vector>
#include< iostream>
int main(int argc,const char * argv [])
{
std :: vector< int> input = {1,2,3,4,5,6,7,8,9};
const int N = 4;
using boost :: adapters :: sliced;
for(auto& e:input | sliced(0,N))
std :: cout< e - < std :: endl;
}
一个重要注意事项:
/ code>不大于
distance(range)
- 这样更安全(和更慢)的版本如下:for(auto& e:input | sliced(0,std :: min(N,input.size())))
所以 - 再次 - 我会使用更简单的旧的C / C ++方法(这是你想避免的问题) p>
I would like to know if there is a nice way to iterate over at most N elements in a container using the range based for loop and/or algorithms from the standard library (that's the whole point, I know I can just use the "old" for loop with a condition).
Basically, I'm looking for something that corresponds to this Python code:
for i in arr[:N]: print(i)
解决方案As I personally would use either this or this answer (+1 for both), just for increasing your knowledge - there are boost adapters you can use. For your case - the sliced seems the most appropriate:
#include <boost/range/adaptor/sliced.hpp> #include <vector> #include <iostream> int main(int argc, const char* argv[]) { std::vector<int> input={1,2,3,4,5,6,7,8,9}; const int N = 4; using boost::adaptors::sliced; for (auto&& e: input | sliced(0, N)) std::cout << e << std::endl; }
One important note: N is required by
sliced
to be not greater thandistance(range)
- so safer(and slower) version is as follows:for (auto&& e: input | sliced(0, std::min(N, input.size())))
So - once again - I would use simpler, old C/C++ approach (this you wanted to avoid in your question ;)
这篇关于有没有办法迭代最多N个元素使用基于范围的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!