c++ vector 反向迭代问题

c++ vector的迭代器(不是反向迭代器)在做反向迭代的时候很容易出现错误,在vs2017下无法通过:Expression: can’t decrement vector iterator before begin,原因是不允许vecvtor.begin()-1。
编译器版本:
在这里插入图片描述
但是牛客网却可以编译通过。。。
有个类似的帖子:
http://compgroups.net/comp.lang.c++.moderated/decrementing-vector-begin-iterator-fo/471397
https://blog.csdn.net/qq_27563511/article/details/81282579
附上牛客网题目和代码:
栈的压入,弹出序列

#include<cstdio>
#include<iostream>
#include<vector>
#include<set>
using namespace std;
class Solution {
public:
	bool IsPopOrder(vector<int> pushV, vector<int> popV) {

		int startNum = popV.front();
		set<int> popNums;

		vector<int>::iterator it1 = pushV.end() - 1;
		vector<int>::iterator it2 = popV.begin() + 1;
		for (; it1 >= pushV.begin(); it1--)
		{
			//等于begin时,break,不能向下减迭代器了
			if (*it1 == startNum)
			{
				popNums.insert(startNum);
				break;
			}
			else if (it1 == pushV.begin())
			{
				//使用这个而不是下面注释的那行,否则对于下面的特定测试用例编译不过,不允许begin()-1
				return false;
			}
			else    popNums.insert(*it1);

		}
		//if (it1 < pushV.begin())    return false;
		if (it1 != pushV.begin())    it1--;
		for (it2 = popV.begin() + 1; it2 < popV.end(); it2++)
		{
			if (popNums.count(*it2) == 0 && *it1 != *it2)
				return false;
			else
			{
				if (*it1 == *it2)
				{
					popNums.insert(*it1);
					if (it1 == pushV.begin())	return true;
					it1--;
				}
			}
		}
		return true;

	}
};
发布了163 篇原创文章 · 获赞 21 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/whimewcm/article/details/89053579