简体   繁体   中英

Range-based for loop on arrays

I'm trying to do something similar to this:

int iArray[16];
int iOtherArray[16];
for ( auto &i: iArray )
{
    iOtherArray[i] = iArray[i];
}

Where the for loops through the number of components the array has, not each individual component. Am I understanding the usage for Range-based for loops correctly?

No, the range -based loop will give you the element values, not indexes.

For a copy operation like this a range-based loop is a poor choice as you have to keep track of two ranges and want cooresponding elements of each. Just use a normal for loop for this.

for(int i = 0; 16 > ndx; ++ndx)
  otherArray[i] = array[i];

您可以只使用标准库中的复制算法:

std::copy(array, array+16, otherArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM