有没有办法使用基于范围的 for 循环迭代最多 N 个元素?
Is there a way to iterate over at most N elements using range-based for loop?
有没有一种很好的方法可以使用标准库中基于范围的 for
循环 and/or 算法来迭代容器中最多 N 个元素(这就是重点,我知道我可以只使用带有条件的“旧”for
循环)。
基本上,我正在寻找与此 Python 代码相对应的内容:
for i in arr[:N]:
print(i)
您可以使用旧的 break
在需要时手动中断循环。它甚至适用于基于范围的循环。
#include <vector>
#include <iostream>
int main() {
std::vector<int> a{2, 3, 4, 5, 6};
int cnt = 0;
int n = 3;
for (int x: a) {
if (cnt++ >= n) break;
std::cout << x << std::endl;
}
}
这是适用于我能想到的所有前向迭代器的最便宜的保存解决方案:
auto begin = std::begin(range);
auto end = std::end(range);
if (std::distance(begin, end) > N)
end = std::next(begin,N);
这可能 运行 通过范围几乎两次,但我看不出有其他方法可以获取范围的长度。
如果您的容器没有(或可能没有)RandomAccessIterator,仍然有办法给这只猫换皮:
int cnt = 0;
for(auto it=container.begin(); it != container.end() && cnt < N ; ++it,++cnt) {
//
}
至少对我来说,它的可读性很强:-)。无论容器类型如何,它都具有 O(N) 复杂度。
因为我个人会使用 or answer (+1 for both), just for increasing your knowledge - there are boost adapters you can use. For your case - the sliced 似乎最合适:
#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;
}
重要说明:sliced
要求 N 不大于 distance(range)
- 因此更安全(更慢)的版本如下:
for (auto&& e: input | sliced(0, std::min(N, input.size())))
所以 - 再一次 - 我会使用更简单的旧 C/C++ 方法(你想在你的问题中避免这种情况;)
此解决方案不会超过 end()
,对于 std::list
(不使用 std::distance
)具有 O(N)
的复杂性,适用于 std::for_each
,并且只需要 ForwardIterator
:
std::vector<int> vect = {1,2,3,4,5,6,7,8};
auto stop_iter = vect.begin();
const size_t stop_count = 5;
if(stop_count <= vect.size())
{
std::advance(stop_iter, n)
}
else
{
stop_iter = vect.end();
}
std::for_each(vect.vegin(), stop_iter, [](auto val){ /* do stuff */ });
它唯一不能做的是与 InputIterator
一起工作,例如 std::istream_iterator
- 你必须为此使用外部计数器。
C++ 很棒,因为您可以编写自己的可怕 解决方案并将它们隐藏在抽象层下
#include <vector>
#include <iostream>
//~-~-~-~-~-~-~- abstraction begins here ~-~-~-~-~-//
struct range {
range(std::vector<int>& cnt) : m_container(cnt),
m_end(cnt.end()) {}
range& till(int N) {
if (N >= m_container.size())
m_end = m_container.end();
else
m_end = m_container.begin() + N;
return *this;
}
std::vector<int>& m_container;
std::vector<int>::iterator m_end;
std::vector<int>::iterator begin() {
return m_container.begin();
}
std::vector<int>::iterator end() {
return m_end;
}
};
//~-~-~-~-~-~-~- abstraction ends here ~-~-~-~-~-//
int main() {
std::vector<int> a{11, 22, 33, 44, 55};
int n = 4;
range subRange(a);
for ( int i : subRange.till(n) ) {
std::cout << i << std::endl; // prints 11, then 22, then 33, then 44
}
}
上面的代码显然缺少一些错误检查和其他调整,但我只是想表达清楚。
这是有效的,因为 range-based for loops 生成类似于以下的代码
{
auto && __range = range_expression ;
for (auto __begin = begin_expr,
__end = end_expr;
__begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
cfr。 begin_expr
和 end_expr
这是一个索引迭代器。主要是样板文件,省略了,因为我很懒。
template<class T>
struct indexT
//: std::iterator< /* ... */ > // or do your own typedefs, or don't bother
{
T t = {};
indexT()=default;
indexT(T tin):t(tin){}
indexT& operator++(){ ++t; return *this; }
indexT operator++(int){ auto tmp = *this; ++t; return tmp; }
T operator*()const{return t;}
bool operator==( indexT const& o )const{ return t==o.t; }
bool operator!=( indexT const& o )const{ return t!=o.t; }
// etc if you want full functionality.
// The above is enough for a `for(:)` range-loop
};
它包装了一个标量类型 T
,并在 *
returns 上包装了一个副本。有趣的是,它也适用于迭代器,这在这里很有用,因为它让我们可以有效地从指针继承:
template<class ItA, class ItB>
struct indexing_iterator:indexT<ItA> {
ItB b;
// TODO: add the typedefs required for an iterator here
// that are going to be different than indexT<ItA>, like value_type
// and reference etc. (for simple use, not needed)
indexing_iterator(ItA a, ItB bin):ItA(a), b(bin) {}
indexT<ItA>& a() { return *this; }
indexT<ItA> const& a() const { return *this; }
decltype(auto) operator*() {
return b[**a()];
}
decltype(auto) operator->() {
return std::addressof(b[**a()]);
}
};
索引迭代器包装了两个迭代器,其中第二个迭代器必须是随机访问的。它使用第一个迭代器获取索引,然后使用该索引从第二个迭代器中查找值。
接下来,我们有一个范围类型。 SFINAE 改进版可以在很多地方找到。它使得在 for(:)
循环中遍历一系列迭代器变得容易:
template<class Iterator>
struct range {
Iterator b = {};
Iterator e = {};
Iterator begin() { return b; }
Iterator end() { return e; }
range(Iterator s, Iterator f):b(s),e(f) {}
range(Iterator s, size_t n):b(s), e(s+n) {}
range()=default;
decltype(auto) operator[](size_t N) { return b[N]; }
decltype(auto) operator[] (size_t N) const { return b[N]; }\
decltype(auto) front() { return *b; }
decltype(auto) back() { return *std::prev(e); }
bool empty() const { return begin()==end(); }
size_t size() const { return end()-begin(); }
};
这里有一些帮助程序可以使 indexT
范围内的工作变得容易:
template<class T>
using indexT_range = range<indexT<T>>;
using index = indexT<size_t>;
using index_range = range<index>;
template<class C>
size_t size(C&&c){return c.size();}
template<class T, std::size_t N>
size_t size(T(&)[N]){return N;}
index_range indexes( size_t start, size_t finish ) {
return {index{start},index{finish}};
}
template<class C>
index_range indexes( C&& c ) {
return make_indexes( 0, size(c) );
}
index_range intersect( index_range lhs, index_range rhs ) {
if (lhs.b.t > rhs.e.t || rhs.b.t > lhs.b.t) return {};
return {index{(std::max)(lhs.b.t, rhs.b.t)}, index{(std::min)(lhs.e.t, rhs.e.t)}};
}
好的,差不多了。
index_filter_it
采用一系列索引和一个随机访问迭代器,并将一系列索引迭代器放入该随机访问迭代器的数据中:
template<class R, class It>
auto index_filter_it( R&& r, It it ) {
using std::begin; using std::end;
using ItA = decltype( begin(r) );
using R = range<indexing_iterator<ItA, It>>;
return R{{begin(r),it}, {end(r),it}};
}
index_filter
获取一个 index_range
和一个随机访问容器,与它们的索引相交,然后调用 index_filter_it
:
template<class C>
auto index_filter( index_range r, C& c ) {
r = intersect( r, indexes(c) );
using std::begin;
return index_filter_it( r, begin(c) );
}
现在我们有:
for (auto&& i : index_filter( indexes(0,6), arr )) {
}
还有中提琴,我们有大型乐器。
可以使用更高级的过滤器。
size_t filter[] = {1,3,0,18,22,2,4};
using std::begin;
for (auto&& i : index_filter_it( filter, begin(arr) ) )
将访问arr
中的1、3、0、18、22、2、4。但是,它不会进行边界检查,除非 arr.begin()[]
边界检查。
上面的代码可能有错误,你应该直接使用boost
。
如果您在 indexT
上实施 -
和 []
,您甚至可以菊花链连接这些范围。
首先我们写一个在给定索引处停止的迭代器:
template<class I>
class at_most_iterator
: public boost::iterator_facade<at_most_iterator<I>,
typename I::value_type,
boost::forward_traversal_tag>
{
private:
I it_;
int index_;
public:
at_most_iterator(I it, int index) : it_(it), index_(index) {}
at_most_iterator() {}
private:
friend class boost::iterator_core_access;
void increment()
{
++it_;
++index_;
}
bool equal(at_most_iterator const& other) const
{
return this->index_ == other.index_ || this->it_ == other.it_;
}
typename std::iterator_traits<I>::reference dereference() const
{
return *it_;
}
};
我们现在可以编写一个算法来从给定范围内生成此迭代器的 rage:
template<class X>
boost::iterator_range<
at_most_iterator<typename X::iterator>>
at_most(int i, X& xs)
{
typedef typename X::iterator iterator;
return std::make_pair(
at_most_iterator<iterator>(xs.begin(), 0),
at_most_iterator<iterator>(xs.end(), i)
);
}
用法:
int main(int argc, char** argv)
{
std::vector<int> xs = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int x : at_most(5, xs))
std::cout << x << "\n";
return 0;
}
自 C++20 you can add the range adaptor std::views::take
from the Ranges library to your range-based for loop. This way you can implement a similar solution to the one in 以来,但未使用 Boost:
int main() {
std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9};
const int N = 4;
for (int i : v | std::views::take(N))
std::cout << i << std::endl;
return 0;
}
这个解决方案的好处是 N
可能比向量的大小大。这意味着,对于上面的示例,使用 N = 13
是安全的;然后将打印完整的矢量。
有没有一种很好的方法可以使用标准库中基于范围的 for
循环 and/or 算法来迭代容器中最多 N 个元素(这就是重点,我知道我可以只使用带有条件的“旧”for
循环)。
基本上,我正在寻找与此 Python 代码相对应的内容:
for i in arr[:N]:
print(i)
您可以使用旧的 break
在需要时手动中断循环。它甚至适用于基于范围的循环。
#include <vector>
#include <iostream>
int main() {
std::vector<int> a{2, 3, 4, 5, 6};
int cnt = 0;
int n = 3;
for (int x: a) {
if (cnt++ >= n) break;
std::cout << x << std::endl;
}
}
这是适用于我能想到的所有前向迭代器的最便宜的保存解决方案:
auto begin = std::begin(range);
auto end = std::end(range);
if (std::distance(begin, end) > N)
end = std::next(begin,N);
这可能 运行 通过范围几乎两次,但我看不出有其他方法可以获取范围的长度。
如果您的容器没有(或可能没有)RandomAccessIterator,仍然有办法给这只猫换皮:
int cnt = 0;
for(auto it=container.begin(); it != container.end() && cnt < N ; ++it,++cnt) {
//
}
至少对我来说,它的可读性很强:-)。无论容器类型如何,它都具有 O(N) 复杂度。
因为我个人会使用
#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;
}
重要说明:sliced
要求 N 不大于 distance(range)
- 因此更安全(更慢)的版本如下:
for (auto&& e: input | sliced(0, std::min(N, input.size())))
所以 - 再一次 - 我会使用更简单的旧 C/C++ 方法(你想在你的问题中避免这种情况;)
此解决方案不会超过 end()
,对于 std::list
(不使用 std::distance
)具有 O(N)
的复杂性,适用于 std::for_each
,并且只需要 ForwardIterator
:
std::vector<int> vect = {1,2,3,4,5,6,7,8};
auto stop_iter = vect.begin();
const size_t stop_count = 5;
if(stop_count <= vect.size())
{
std::advance(stop_iter, n)
}
else
{
stop_iter = vect.end();
}
std::for_each(vect.vegin(), stop_iter, [](auto val){ /* do stuff */ });
它唯一不能做的是与 InputIterator
一起工作,例如 std::istream_iterator
- 你必须为此使用外部计数器。
C++ 很棒,因为您可以编写自己的可怕 解决方案并将它们隐藏在抽象层下
#include <vector>
#include <iostream>
//~-~-~-~-~-~-~- abstraction begins here ~-~-~-~-~-//
struct range {
range(std::vector<int>& cnt) : m_container(cnt),
m_end(cnt.end()) {}
range& till(int N) {
if (N >= m_container.size())
m_end = m_container.end();
else
m_end = m_container.begin() + N;
return *this;
}
std::vector<int>& m_container;
std::vector<int>::iterator m_end;
std::vector<int>::iterator begin() {
return m_container.begin();
}
std::vector<int>::iterator end() {
return m_end;
}
};
//~-~-~-~-~-~-~- abstraction ends here ~-~-~-~-~-//
int main() {
std::vector<int> a{11, 22, 33, 44, 55};
int n = 4;
range subRange(a);
for ( int i : subRange.till(n) ) {
std::cout << i << std::endl; // prints 11, then 22, then 33, then 44
}
}
上面的代码显然缺少一些错误检查和其他调整,但我只是想表达清楚。
这是有效的,因为 range-based for loops 生成类似于以下的代码
{
auto && __range = range_expression ;
for (auto __begin = begin_expr,
__end = end_expr;
__begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
cfr。 begin_expr
和 end_expr
这是一个索引迭代器。主要是样板文件,省略了,因为我很懒。
template<class T>
struct indexT
//: std::iterator< /* ... */ > // or do your own typedefs, or don't bother
{
T t = {};
indexT()=default;
indexT(T tin):t(tin){}
indexT& operator++(){ ++t; return *this; }
indexT operator++(int){ auto tmp = *this; ++t; return tmp; }
T operator*()const{return t;}
bool operator==( indexT const& o )const{ return t==o.t; }
bool operator!=( indexT const& o )const{ return t!=o.t; }
// etc if you want full functionality.
// The above is enough for a `for(:)` range-loop
};
它包装了一个标量类型 T
,并在 *
returns 上包装了一个副本。有趣的是,它也适用于迭代器,这在这里很有用,因为它让我们可以有效地从指针继承:
template<class ItA, class ItB>
struct indexing_iterator:indexT<ItA> {
ItB b;
// TODO: add the typedefs required for an iterator here
// that are going to be different than indexT<ItA>, like value_type
// and reference etc. (for simple use, not needed)
indexing_iterator(ItA a, ItB bin):ItA(a), b(bin) {}
indexT<ItA>& a() { return *this; }
indexT<ItA> const& a() const { return *this; }
decltype(auto) operator*() {
return b[**a()];
}
decltype(auto) operator->() {
return std::addressof(b[**a()]);
}
};
索引迭代器包装了两个迭代器,其中第二个迭代器必须是随机访问的。它使用第一个迭代器获取索引,然后使用该索引从第二个迭代器中查找值。
接下来,我们有一个范围类型。 SFINAE 改进版可以在很多地方找到。它使得在 for(:)
循环中遍历一系列迭代器变得容易:
template<class Iterator>
struct range {
Iterator b = {};
Iterator e = {};
Iterator begin() { return b; }
Iterator end() { return e; }
range(Iterator s, Iterator f):b(s),e(f) {}
range(Iterator s, size_t n):b(s), e(s+n) {}
range()=default;
decltype(auto) operator[](size_t N) { return b[N]; }
decltype(auto) operator[] (size_t N) const { return b[N]; }\
decltype(auto) front() { return *b; }
decltype(auto) back() { return *std::prev(e); }
bool empty() const { return begin()==end(); }
size_t size() const { return end()-begin(); }
};
这里有一些帮助程序可以使 indexT
范围内的工作变得容易:
template<class T>
using indexT_range = range<indexT<T>>;
using index = indexT<size_t>;
using index_range = range<index>;
template<class C>
size_t size(C&&c){return c.size();}
template<class T, std::size_t N>
size_t size(T(&)[N]){return N;}
index_range indexes( size_t start, size_t finish ) {
return {index{start},index{finish}};
}
template<class C>
index_range indexes( C&& c ) {
return make_indexes( 0, size(c) );
}
index_range intersect( index_range lhs, index_range rhs ) {
if (lhs.b.t > rhs.e.t || rhs.b.t > lhs.b.t) return {};
return {index{(std::max)(lhs.b.t, rhs.b.t)}, index{(std::min)(lhs.e.t, rhs.e.t)}};
}
好的,差不多了。
index_filter_it
采用一系列索引和一个随机访问迭代器,并将一系列索引迭代器放入该随机访问迭代器的数据中:
template<class R, class It>
auto index_filter_it( R&& r, It it ) {
using std::begin; using std::end;
using ItA = decltype( begin(r) );
using R = range<indexing_iterator<ItA, It>>;
return R{{begin(r),it}, {end(r),it}};
}
index_filter
获取一个 index_range
和一个随机访问容器,与它们的索引相交,然后调用 index_filter_it
:
template<class C>
auto index_filter( index_range r, C& c ) {
r = intersect( r, indexes(c) );
using std::begin;
return index_filter_it( r, begin(c) );
}
现在我们有:
for (auto&& i : index_filter( indexes(0,6), arr )) {
}
还有中提琴,我们有大型乐器。
可以使用更高级的过滤器。
size_t filter[] = {1,3,0,18,22,2,4};
using std::begin;
for (auto&& i : index_filter_it( filter, begin(arr) ) )
将访问arr
中的1、3、0、18、22、2、4。但是,它不会进行边界检查,除非 arr.begin()[]
边界检查。
上面的代码可能有错误,你应该直接使用boost
。
如果您在 indexT
上实施 -
和 []
,您甚至可以菊花链连接这些范围。
首先我们写一个在给定索引处停止的迭代器:
template<class I>
class at_most_iterator
: public boost::iterator_facade<at_most_iterator<I>,
typename I::value_type,
boost::forward_traversal_tag>
{
private:
I it_;
int index_;
public:
at_most_iterator(I it, int index) : it_(it), index_(index) {}
at_most_iterator() {}
private:
friend class boost::iterator_core_access;
void increment()
{
++it_;
++index_;
}
bool equal(at_most_iterator const& other) const
{
return this->index_ == other.index_ || this->it_ == other.it_;
}
typename std::iterator_traits<I>::reference dereference() const
{
return *it_;
}
};
我们现在可以编写一个算法来从给定范围内生成此迭代器的 rage:
template<class X>
boost::iterator_range<
at_most_iterator<typename X::iterator>>
at_most(int i, X& xs)
{
typedef typename X::iterator iterator;
return std::make_pair(
at_most_iterator<iterator>(xs.begin(), 0),
at_most_iterator<iterator>(xs.end(), i)
);
}
用法:
int main(int argc, char** argv)
{
std::vector<int> xs = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int x : at_most(5, xs))
std::cout << x << "\n";
return 0;
}
自 C++20 you can add the range adaptor std::views::take
from the Ranges library to your range-based for loop. This way you can implement a similar solution to the one in
int main() {
std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9};
const int N = 4;
for (int i : v | std::views::take(N))
std::cout << i << std::endl;
return 0;
}
这个解决方案的好处是 N
可能比向量的大小大。这意味着,对于上面的示例,使用 N = 13
是安全的;然后将打印完整的矢量。