通过引用传递一个向量,并在基于范围的for循环中更改其值? [英] Passing a vector by reference and changing its values in a range-based for loop?
本文介绍了通过引用传递一个向量,并在基于范围的for循环中更改其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过执行类似于以下函数的方式更改向量的值:
I'm trying to change the values of a vector by doing something similar to the following function:
vector<int> Question2_Part3(vector<int> &v){
for(auto elem : v){
elem *= 2;
cout << elem << " ";
}
cout << "\n" << endl;
return v;
}
这是可能吗?我知道在我的for循环中, elem
的值正在改变。我可以有同样的输出,同时还改变 v
中的值,仍然使用基于范围的循环?
Is this possible? I know that in my for loop, it is the value of elem
that is changing. Can I have the same output while also changing the values in v
and still use a range-based for loop?
推荐答案
是的,但可以使用参考
for (auto &elem : v) {
elem *= 2;
cout << elem << " ";
}
这也更有效,因为它避免将每个向量元素复制到变量。实际上如果你不想改变你应该做的元素
This is also more efficient as it avoids copying each vector element to a variable. Actually if you didn't want to change the elements you should do
for (const auto &elem : v) {
cout << elem << " ";
}
这篇关于通过引用传递一个向量,并在基于范围的for循环中更改其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文