zoukankan      html  css  js  c++  java
  • 如何在循环中访问list前后元素

    1. 复制整个list

    Copying and incrementing/decrementing the copy is the only way it can be done.

    You can write wrapper functions to hide it (and as mentioned in answers, C++11 has std::prev/std::next which do just that (and Boost defines similar functions). But they are wrappers around this "copy and increment" operation, so you don't have to worry that you're doing it "wrong".

    2. 使用C++0x或者C++11中的 pre 和 next

    In C++0x, this functionality is neatly wrapped up in the std::prev function, which your C++ Standard Library implementation may support. If not, it looks something like this:

    template <typename BidiIt>
    BidiIt prev(BidiIt x, typename std::iterator_traits<BidiIt>::difference_type n=1)
    {
        std::advance(x, -n);
        return x;
    }

    For C++11, there are the two methods you are looking for called std::prev and std::next. You can find them in the iterator library.

    Example from cppreference.com

    #include <iostream>
    #include <iterator>
    #include <vector>
    
    int main() 
    {
        std::list<int> v{ 3, 1, 4 };
    
        auto it = v.begin();
    
        auto nx = std::next(it, 2);
    
        std::cout << *it << ' ' << *nx << '
    ';
    }

    Output:

    3 4

    3. 使用Boost中的 prior 和 next

    A simple precanned solution are prior and next from Boost.utility. They take advantage of operator-- and operator++ but don't require you to create a temporary.

    4. 创建新的iterator

    std::list is only bidirecitonally iterable, so you can only move the iterator one position at a time. You thus need to create a new iterator:

    iter_copy = iter;
    --iter;

    Obviously, you are responsible for ensuring that a previous element actually exists before you decrement the iterator.

     

    Reference:

    http://stackoverflow.com/questions/10137214/how-get-next-previous-element-in-stdlist-without-incrementing-decrementing

    http://stackoverflow.com/questions/5586377/how-to-access-the-previous-element-in-a-c-list-iterator-loop

  • 相关阅读:
    .NET.GC 浅谈.net托管程序中的资源释放问题 (转帖)
    VB 中实现 For Each
    创建 ODBC 数据源以连接到 Windows CE 设备上的Sybase数据库
    VB 调用水晶报表2
    VC数据类型
    对.Net 垃圾回收Finalize 和Dispose的理解
    C# 播放器
    [转载]帮助C#菜鸟进入GDI+开发
    线程间操作无效: 从不是创建控件 的线程访问它
    VB.Net 中 WithEvents、AddHandler
  • 原文地址:https://www.cnblogs.com/learnopencad/p/4300471.html
Copyright © 2011-2022 走看看