您的位置:首页 > 编程语言 > C语言/C++

C++ STL 迭代器方法 之 advance与prev 方法 浅析

2015-07-28 15:21 567 查看
【摘要】

迭代器是STL中重要的一支,prev和distance是其基本方法。distance方法十分简单,就不在此赘述,现主要对prev方法以及其相关方法——advance方法作简要介绍与使用说明,并在文末附上代码示例。

【Advance 方法】

Advance iterator

Advances the iterator it by n element positions.

If it is a random-access iterator, the function uses just once operator+ or operator-. Otherwise, the function uses repeatedly the increase or decrease operator (operator++ or operator--)
until n elements have been advanced.



advance迭代器就是将迭代器it,移动n位。如果it是随机访问迭代器,那么函数进行1次运算符计算操作,否则函数将对迭代器进行n次迭代计算操作。

代码示例


// advance example
#include <iostream>     // std::cout
#include <iterator>     // std::advance
#include <list>         // std::list

int main () {
  std::list<int> mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

  std::list<int>::iterator it = mylist.begin();

  std::advance (it,5);

  std::cout << "The sixth element in mylist is: " << *it << '\n';// 输出 50

  return 0;
}
解析

注意,移动5次,输出的是第6个元素而不是第5个元素。



【Prev 方法】

Get iterator to previous element
Returns an iterator pointing to the element that it would be pointing to if advanced
-n
positions.

If it is a random-access iterator, the function uses just once
operator+
or
operator-
. Otherwise, the
function uses repeatedly the increase or decrease operator (
operator++
or
operator--
) on the copied iterator until n elements have been advanced.

如果是随机访问迭代器,就只执行一次运算符操作(+或-),否则,执行n次持续的递减或递增操作。



代码示例

#include <iostream>     // std::cout
#include <iterator>     // std::advance
#include <list>         // std::list
#include <algorithm>

int main () {
  std::list<int> mylist;
  for (int i=0; i<10; i++) mylist.push_back (i*10);

//std::cout<<*upper_bound(mylist.begin(), mylist.end(), 100)<<std::endl;// 抛出异常
  std::cout<<*lower_bound(mylist.begin(), mylist.end(), 0)<<std::endl;// 输出 0
  std::cout<<*prev(upper_bound(mylist.begin(), mylist.end(), 100))<<std::endl;// 输出 90
std::cout<<*prev(++upper_bound(mylist.begin(), mylist.end(), 90))<<std::endl;// 抛出异常
//std::cout<<*prev(lower_bound(mylist.begin(), mylist.end(), 0))<<std::endl;// 抛出异常
  return 0;
}

解析

prev在VC6.0之中不能实现,在VS2010之中可以实现。实际实现的操作是将迭代器递减一个单位长度而已,并未见所谓的递增操作或者根据是否作为随机迭代器时的一次或者n次操作!

【复盘】

详见:LeetCode 之 Search for a Range(查找)

详址:/article/2619958.html



class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        const int l = distance(nums.begin(), lower_bound(nums.begin(), nums.end(), target));
        const int u = distance(nums.begin(), --upper_bound(nums.begin(), nums.end(), target));
        if (nums[l] != target) // not found
        	return vector<int> { -1, -1 };
        else
        	return vector<int> { l, u };
    }
};

解析:

源码验证AC,只是在原来基础上将 “prev(... )”改为 “--(... )”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: