有没有办法使用基于范围的 for 循环迭代最多 N 个元素?

问题描述 投票:0回答:10

有没有一种很好的方法可以使用基于范围的

for
循环和/或标准库中的算法来迭代容器中最多N个元素(这就是重点,我知道我可以只使用“旧”
 for
有条件循环)。

基本上,我正在寻找与此Python代码相对应的东西:

for i in arr[:N]:
    print(i)
c++ c++11 stl c++14
10个回答
39
投票

我个人会使用 thisthis 答案(两者都+1),只是为了增加您的知识 - 您可以使用升压适配器。对于您的情况 - 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++ 方法(这是你想在问题中避免的;)


14
投票

这是最便宜的保存解决方案,适用于我能想到的所有前向迭代器:

auto begin = std::begin(range);
auto end = std::end(range);
if (std::distance(begin, end) > N)
    end = std::next(begin,N);

这可能会几乎遍历该范围两次,但我看不到其他方法来获取该范围的长度。


8
投票

您可以在需要时使用旧的

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;
    }
}

7
投票

C++ 很棒,因为你可以编写自己的hideous解决方案并将它们隐藏在抽象层下

#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
    }
}

实例

上面的代码显然缺少一些错误检查和其他调整,但我只是想清楚地表达想法。

这是有效的,因为基于范围的 for 循环产生类似于以下的代码

{
  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


6
投票

如果您的容器没有(或可能没有)RandomAccessIterator,仍然有一种方法可以给这只猫剥皮:

int cnt = 0;
for(auto it=container.begin(); it != container.end() && cnt < N ; ++it,++cnt) {
  //
}

至少对我来说,它非常可读:-)。无论容器类型如何,它的复杂度都是 O(N)。


5
投票

这是一个索引迭代器。主要是样板文件,省略它,因为我很懒。

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
,并在
*
上返回一个副本。有趣的是,它也适用于迭代器,这在这里很有用,因为它让我们可以有效地从指针继承:

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
,您甚至可以以菊花链方式连接这些范围。


3
投票

C++20 起,您可以将范围适配器

std::views::take
Ranges 库 添加到基于范围的 for 循环。通过这种方式,您可以实现与 PiotrNycz 的答案中的解决方案类似的解决方案,但不使用 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
是安全的;然后将打印完整的向量。

Wandbox 上的代码


2
投票

这个解决方案不会超越

end()
,具有
O(N)
std::list
复杂性(不使用
std::distance
)与
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
- 您必须为此使用外部计数器。


2
投票

首先我们编写一个在给定索引处停止的迭代器:

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_;
  }
};

我们现在可以编写一个算法来使该迭代器在给定范围内进行迭代:

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;
}

0
投票

我最喜欢的答案(现在我们有了 C++20)是这样的:

for (const auto& foo : std::span{bar.begin(), num_iterations}) {
    // stuff
}

使用这样的跨度,我们可以使用基于范围的

for

轻松迭代任何子序列
for (const auto& foo : std::span{bar.begin() + subsequence_start, num_iterations}) {
    // stuff
}
© www.soinside.com 2019 - 2024. All rights reserved.