C++ std::advance的使用教程

298 阅读1分钟

std::advance 是一个 C++ 标准库中的函数,用于将迭代器向前移动指定的步数。它的基本用法如下:

#include <iterator>

// ...

std::list<int>::iterator it = myList.begin();
std::advance(it, n);  // 将迭代器 it 向前移动 n 步

其中,it 是一个迭代器,n 是要向前移动的步数。请注意,std::advance 并不返回新的迭代器,而是直接修改传入的迭代器 it。如果 n 是正数,迭代器将向前移动;如果 n 是负数,迭代器将向后移动。

以下是一个示例,演示如何使用 std::advance 将迭代器移动到 std::list 中的第5个元素:

#include <iostream>
#include <list>
#include <iterator>

int main() {
    std::list<int> myList = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    int targetIndex = 5;
    
    std::list<int>::iterator it = myList.begin();
    
    // 使用 std::advance 移动迭代器到第5个位置
    std::advance(it, targetIndex - 1);  // 减1因为索引从1开始
    
    if (it != myList.end()) {
        // 找到了第5个元素,可以访问它
        int fifthElement = *it;
        std::cout << "第5个元素是: " << fifthElement << std::endl;
    } else {
        // 如果列表长度小于5或者没有第5个元素,输出错误信息
        std::cout << "没有第5个元素或列表长度不足5" << std::endl;
    }
    
    return 0;
}

在这个示例中,std::advance 被用来将迭代器 it 移动到第5个元素的位置。请注意,我们需要将 targetIndex 减1,因为索引从1开始,而不是从0开始。