我不熟悉这种语法:++fCount[index]
。其中 list
是另一个 vector 。
我以为它与下面的相同,但事实并非如此:
int i = 0;
vector<int> fCount(1001,0);
for(auto index : list)
{
fCount[i] = index;
i++;
}
一段代码:
vector<int> fCount(1001,0);
for(auto index : list)
{
++fCount[index];
}
最佳答案
vector::operator[]
返回对给定索引处的元素的引用。
++
increment operator增加变量的值。
您显示的两个代码示例并不等效。
第一个代码循环遍历list
,将其每个元素按原样分配给fCount
的顺序元素。 range-for
循环不提供对正在迭代的元素的索引的访问,因此使用单独的 i
变量来索引 fCount
,其中 i
初始化为索引 0,而 i++
每次都会将 i
的值增加 1
循环迭代。例如:
vector<int> list = {5, 10, 15, 20, ...};
int i = 0;
vector<int> fCount(1001,0);
for(auto index : list)
{
fCount[i] = index;
i++;
}
这有效地填充了fCount
,如下所示:
vector<int> fCount(1001,0);
fCount[0] = 5;
fCount[1] = 10;
fCount[2] = 15;
fCount[3] = 20;
...
第二个代码使用 list
的每个元素作为 fCount
的索引,使用 ++
运算符递增每个元素的值fCount
的索引元素。这是因为 ++fCount[index]
使用前缀增量运算符,该运算符具有 lower precedence比 vector::operator[]
更高,因此 ++fCount[index]
被解析为 ++(fCount[index])
,而不是(++fCount)[index]
(IOW,fCount
首先被索引,然后增量应用于 operator[]
返回的内容)。由于 fCount
在循环之前用 0
初始化,因此在循环结束后,索引的每个元素的值将恰好为 1
。例如:
vector<int> list = {5, 10, 15, 20, ...};
vector<int> fCount(1001,0);
for(auto index : list)
{
++fCount[index];
}
这有效地填充了fCount
,如下所示:
vector<int> fCount(1001,0);
fCount[5] += 1;
fCount[10] += 1;
fCount[15] += 1;
fCount[20] += 1;
...
关于c++ - 容器前的 a++ 与将索引移动 1 相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71327479/