容器使用tips | 迭代器

迭代器

distance

函数模板std::distance的功能是,计算first和last之间,元素的个数
函数模板的内部实现方法:
如果是随机访问迭代器,函数会使用-运算符进行计算。否则,函数使用++运算符进行计算

相当于计算半开区间(first, last]的元素个数
想要得到闭区间的元素个数,需要+1
(begin(), end()]会得到容器的元素个数,但这种情况用size()就足够了

template<class InputIterator>  typename iterator_traits<InputIterator>::difference_type
distance (InputIterator first, InputIterator last);

举个例子

    vector<int> vec{1,2,3,4,5,6,7,8};
    auto it = vec.begin();
    ++it;
    cout << "迭代器当前指向元素: " << *it << endl;
    cout << distance(vec.begin(), it) << endl;

得到的输出如下

image

使用该函数模板可以获取元素在容器中的顺序/倒叙偏移量

    cout << "迭代器顺序为" << distance(vec.begin(), it) + 1 << endl;
    cout << "迭代器倒序为" << distance(it, vec.end()) << endl;		//	注意,倒序不需要+1

输出结果如下

image

advance

函数模板std::advance的功能是,将迭代器推进n个元素位置
如果是随机访问迭代器,函数只使用一次+ 或 -运算符。否则,函数使用++ 或 --运算符直到推进了n个元素

template <class InputIterator, class Distance>
void advance (InputIterator& it, Distance n);

举个例子

    vector<int> vec{1,2,3,4,5,6,7,8};
    auto it = vec.begin();
    advance(it, 5);
    cout << "迭代器当前指向元素: " << *it << endl;
    advance(it, -3);
    cout << "迭代器当前指向元素: " << *it << endl;

输出结果为

image

使用时当心迭代器越界问题

next | prev

函数模板std::next() | std::prev()的功能分别对应于advance的正数和负数情况

posted @ 2024-05-09 11:40  lifeAddicted  阅读(20)  评论(0)    收藏  举报