C ++中的迭代器开始/结束与a:collection

时间:2019-01-30 02:42:15

标签: c++ iterator

有人能启发我之间的区别

for( auto a : world )

for( auto a=world.begin() ; a != world.end(); a++ )

前者是否复制了向量/数组[world]的(深层)副本?如果a在循环内更改,则更改似乎在前者中丢失,而在后者中保留。

TIA 理查德

2 个答案:

答案 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是迭代器中值的副本,对其的更改不会影响从其迭代的集合。