为什么代码不使用Pre/Post增量运算符来处理?
以下代码是关于在给定向量中查找重复值。当我使用Post/Pre递增运算符而不是下面使用的正常算术操作时,它不起作用。可能是什么原因?
class Solution {
public:
int findDuplicate(vector<int>& nums)
{
int d=0;
auto it1=nums.begin();
auto it2=nums.end();
vector<int>::iterator it3;
while (it1 != it2)
{
it3 = it1 + 1; //it3=it1++ or it3=++it1 ;
while (it3 != it2)
{
if (*(it3)==*(it1))
{
d=*(it3);
break;
}
else
it3++;
}
if(d)
break;
it1 += 1; //it1++ or ++it1;
}
return d;
}
};
The below code is about finding duplicate value in the given vector. When I am using the post/pre increment operator instead of normal arithmetic operation used below, it's not working. What might be the reason??
class Solution {
public:
int findDuplicate(vector<int>& nums)
{
int d=0;
auto it1=nums.begin();
auto it2=nums.end();
vector<int>::iterator it3;
while (it1 != it2)
{
it3 = it1 + 1; //it3=it1++ or it3=++it1 ;
while (it3 != it2)
{
if (*(it3)==*(it1))
{
d=*(it3);
break;
}
else
it3++;
}
if(d)
break;
it1 += 1; //it1++ or ++it1;
}
return d;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将与插入前或后期一起工作。由于您没有使用增量的
it1
做任何事情,因此在这里使用的是什么都没关系。这些选项中的任何三个都将起作用。这是行为真正改变的地方
。它将
IT3
设置为一个pastit1
,并且不修改it1
。这也将
IT3
设置为一个pastit1
,但是在此过程中,它也会增加it1
,您不想要。这是最糟糕的。它将it1 。因此,没有什么最终以您想要的值。
IT3
设置为it1
(而不是一个past),然后在增量之后如果您真的想在此处使用增量运算符,则可以
这样做将会给出
it3
it1
的值,然后增量IT3
。但这很丑陋。没有真正的理由偏离it3 = it1 + 1;
。This will work with either pre- or post-increment. Since you're not doing anything with the incremented
it1
, it doesn't matter which you use here. Any 3 of these options will work.This is where the behavior really changes
Does what you want. It sets
it3
to one-pastit1
and does not modifyit1
.This also sets
it3
to one-pastit1
, but in the process, it incrementsit1
as well, which you do not want.This is the worst of the bunch. It sets
it3
toit1
(NOT one-past), and then after, incrementsit1
. So nothing ends up with the values you want.If you really wanted to use the increment operator here, you could do
This would give
it3
it1
's value, and then incrementit3
. But this is pretty ugly. There's no real reason to deviate fromit3 = it1 + 1;
.