gpt4 book ai didi

c++ - 迭代器操作不起作用

转载 作者:行者123 更新时间:2023-11-30 01:09:19 25 4
gpt4 key购买 nike

出于某种原因,在此函数中,它计算两个或多个相同值的“团 block ”:

#include <iostream>
#include <iterator>
#include <set>

int countClumps(multiset<int> set)
{
int clumps = 0;

for (multiset<int>::const_iterator iter(set.begin()), end(set.end()); iter != end; ++iter)
{
if (iter == iter[1] && iter != iter[-1])
{
clumps += 1;
}
}
return clumps;
}

我收到错误消息“没有运算符‘[]’匹配这些操作数”。为什么会这样?我认为像 iter[i] 和 *(iter + i) 这样的东西是标准操作?我确实尝试过 *(iter + 1) 但这给了我相同的操作数错误但带有 +。是否有我忘记包含的内容?

最佳答案

I get the error "no operator '[]' matches these operands". Why would this happen?

那是因为operator[] multiset<int>::const_iterator 不支持.

I thought stuff like iter[i] and *(iter + i) were standard operations?

你想错了。

I did try *(iter + 1) but that gave me the same operand error but with +. Was there something that I've forgotten to include?

operator+ multiset<int>::const_iterator 之间不支持和一个 int .因此,iter + 1不是有效的表达式。

您没有忘记添加任何内容。您正在尝试对象类型不支持的操作。

您将不得不重新考虑您的代码。


按照以下实现方式应该可以工作。

int countClumps(multiset<int> set)
{
int clumps = 0;
int previousNumber = 0;

multiset<int>::const_iterator iter(set.begin());
multiset<int>::const_iterator end(set.end());

// Account for empty input.
if ( iter != end )
{
previousNumber = *iter;

for (++iter; iter != end; )
{
if ( previousNumber == *iter )
{
++clumps;

// Skip the rest of the clump
for ( ++iter; iter != end && previousNumber == *iter ; ++iter );
}
else
{
++iter;
}

if ( iter != end )
{
previousNumber = *iter;
}

}
}
return clumps;
}

关于c++ - 迭代器操作不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40520466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com