代码之家  ›  专栏  ›  技术社区  ›  Francis Cugler

阻止迭代器遍历容器的结尾

  •  1
  • Francis Cugler  · 技术社区  · 7 年前

    我在自己工作 for_each 按某个整数键入函数 N

    这就是我的函数当前的样子:

    template<typename Container, typename Function>
    void for_each_by_n( Container&& cont, Function f, unsigned increment_by ) {
        using std::begin;
        auto it = begin(cont);
    
        using std::end;
        auto end_it = end(cont);
    
        while ( it != end_it ) { // traverse the full container
            f(*it);  // call the function pointer - object etc.
            for ( unsigned n = 0; n < increment_by; ++n ) {
                // here I want to increment the pointer as long as the next iteration of
                // increment_by is within the bounds of the range of the container
                if ( .... tried many things .... ) return; // and or break;
                ++it;
            }
        }
    }
    

    我最后一次尝试内部if语句是这样的:

    if ( n % increment_by > (cont.size() - n) ) return; // and or break;
    

    但是,我不断得到一个调试断言失败,我不能迭代超过容器索引的末尾。这让我很困惑,我不知道如何防止迭代结束。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Francis Cugler    7 年前

    好吧,我离开我的电脑大约30秒到1分钟,然后它来找我。我想得太多了,其实只是个简单的解决办法。

    if ( it == end_it ) return;
    

    现在它可以正常工作了。不需要根据索引指针与端点的比较位置进行计算。我所要做的就是比较它们是否相等,如果相等就返回。

    所以完整的函数现在看起来是这样的:

    // positive direction from begin to end only
    template<typename Container, typename Function>
    void for_each_by_n(Container&& cont, Function f, unsigned increment_by) {
        using std::begin;
        auto it = begin(cont);
    
        using std::end;
        auto end_it = end(cont);
    
        while (it != end_it ) {
            f(*it);
            for ( unsigned n = 0; n < increment_by; ++n ) {
                if (it == end_it) {
                    return;
                }
                ++it;
            }
        }
    }
    

        2
  •  0
  •   MSalters    7 年前

    cont ,每个块都是 increment_by 元素。因此有 cont.size()/increment_by 大块。无需检查是否到达最后一个迭代器,只需计算块数。

    ++it . 使用 std::advance(increment_by) ,这对于随机访问迭代器来说要快得多。