[英]Why is this swap method not working?
Why does the below two snippets of code have different results? 为什么以下两个代码片段会有不同的结果? I want to add a 1 in front of digits, which is a vector of integers.
我想在数字前面添加1,它是整数的向量。 But the second snippet does not properly swap.
但是第二个片段没有正确交换。
int tmpInt(1);
for (int i=0; i<digits.size(); i++){
swap(tmpInt, digits[i]);
}
digits.push_back(tmpInt);
versus: 与:
int tmpInt(1);
for (auto it : digits){
swap(tmpInt, it);
}
digits.push_back(tmpInt);
for (auto it : digits){
The range variable gets essentially copied by value, from the sequence, so 范围变量本质上是从序列中按值复制的,因此
swap(tmpInt, it);
all this is doing is swapping between tmpInt
and a temporary range variable. 这一切都是在
tmpInt
和一个临时范围变量之间交换。
You need to use a reference, in order to get equivalent results with the first example: 您需要使用一个引用,以便获得与第一个示例相同的结果:
for (auto &it : digits){
swap(tmpInt, it);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.