c++ 取消引用迭代器时 x++ 和 x = x + 1 之间的区别
c++ difference between x++ and x = x + 1 when dereferencing iterators
我想知道是否有人可以向我解释在取消引用迭代器时增量运算符 ++
和使用 ...=... + 1
之间的区别。我编写了以下一小段代码来对 10 个 bin 中的数字进行排序:
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::cin;
int main()
{
vector<unsigned> vec(11,0);
unsigned num;
while(cin >> num){
if(num < 100)
*(vec.begin() + num/10) = *(vec.begin() + num/10) + 1;
else ;
}
for(vector<unsigned>::iterator it = vec.begin(); it != vec.end(); it++)
cout << *it << endl;
return 0;
}
当我更改此代码的以下部分时:
*(vec.begin() + num/10) = *(vec.begin() + num/10) + 1;
至:
*(vec.begin() + num/10)++;
代码不再有效。即每个 bin 中的数字数量保持为 0。
谁能给我解释一下这两行代码的区别?是因为操作顺序吗?也许它先递增然后取消引用?但如果是这样我不明白为什么。
顺便说一句:我在 c++98 模式下使用了最新版本的 g++
++
的优先级高于*
,所以你的表达式被解析成这样:
*((vec.begin() + num/10)++); //increment, then dereference
您需要明确排序:
(*(vec.begin() + num/10))++;
请注意,预增量不需要副本,因此如果您不需要访问以前的值,通常更可取:
++(*(vec.begin() + num/10));
话虽如此,台词还是很吵,不清楚,如果我是你,我会把表情分开:
if(num < 100){
auto position = vec.begin() + num/10;
++(*position);
}
甚至更好(@dascandy 建议):
if (num < 100) {
++vec[num/10];
}
我想知道是否有人可以向我解释在取消引用迭代器时增量运算符 ++
和使用 ...=... + 1
之间的区别。我编写了以下一小段代码来对 10 个 bin 中的数字进行排序:
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::cin;
int main()
{
vector<unsigned> vec(11,0);
unsigned num;
while(cin >> num){
if(num < 100)
*(vec.begin() + num/10) = *(vec.begin() + num/10) + 1;
else ;
}
for(vector<unsigned>::iterator it = vec.begin(); it != vec.end(); it++)
cout << *it << endl;
return 0;
}
当我更改此代码的以下部分时:
*(vec.begin() + num/10) = *(vec.begin() + num/10) + 1;
至:
*(vec.begin() + num/10)++;
代码不再有效。即每个 bin 中的数字数量保持为 0。
谁能给我解释一下这两行代码的区别?是因为操作顺序吗?也许它先递增然后取消引用?但如果是这样我不明白为什么。
顺便说一句:我在 c++98 模式下使用了最新版本的 g++
++
的优先级高于*
,所以你的表达式被解析成这样:
*((vec.begin() + num/10)++); //increment, then dereference
您需要明确排序:
(*(vec.begin() + num/10))++;
请注意,预增量不需要副本,因此如果您不需要访问以前的值,通常更可取:
++(*(vec.begin() + num/10));
话虽如此,台词还是很吵,不清楚,如果我是你,我会把表情分开:
if(num < 100){
auto position = vec.begin() + num/10;
++(*position);
}
甚至更好(@dascandy 建议):
if (num < 100) {
++vec[num/10];
}