有人能启发我之间的区别
for( auto a : world )
和
for( auto a=world.begin() ; a != world.end(); a++ )
前者是否复制了向量/数组[world]的(深层)副本?如果a
在循环内更改,则更改似乎在前者中丢失,而在后者中保留。
TIA 理查德
答案 0 :(得分:4)
否,第一个循环不会整体复制 function nameCheck() {
alert("test");
if(!localStorage.getItem("name")) {
var name = prompt("Please enter your name");
localStorage.setItem("name", name);
location.reload();
} else {
document.getElementById("welcome").innerHTML = "Hello, " + localStorage.getItem("name");
}
}
的完整副本,但是在每次迭代时,将world
中的一项复制到{{ 1}}。
如果您想对world
进行更改并使它们影响原始集合,通常需要声明a
作为参考:
a
在这种情况下,a
是对std::vector<int> world;
// add 2 to each item in `world`:
for( auto &a : world )
a += 2;
中项目的引用,因此将其添加会修改a
中的项目。
答案 1 :(得分:4)
for( auto a : world ) { ...something... }
大致等同于
for( auto it = world.begin(); it != world.end(); ++it ) {
auto a = *it;
{ ...something... } }
所以a
是迭代器中值的副本,对其的更改不会影响从其迭代的集合。