I need some explanation for the following c++ syntax:
for(const auto& ioDev : deviceList)
given that:
std::vector<Device *> deviceList
Specifically, I am confused about ':' and the usage of 'auto'?
The syntax of for loop in c language is given below: for(Expression 1; Expression 2; Expression 3){ //code to be executed. }
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.
Example 1: for loop // Print numbers from 1 to 10 #include <stdio.h> int main() { int i; for (i = 1; i < 11; ++i) { printf("%d ", i); } return 0; } Run Code. Output 1 2 3 4 5 6 7 8 9 10. i is initialized to 1. The test expression i < 11 is evaluated.
The meaning of colon in c++ The idea is to loop through each element in the array (or vector, or other iterable). The element variable is each element of the array, moving to the next element at the start of each iteration.
As described in the answer by Chad, your for-loop iterates over your vector
, using its begin
and end
iterators. That is the behavior of the colon :
syntax.
Regarding your const auto &
syntax: you should imagine what code comes out of it:
// "i" is an iterator const auto& ioDev = *i;
The expression *i
is (a reference to) the type of elements in the container: Device *
. This is the deduced type of auto
. Because you have const &
appended to your auto
, the variable ioDev
is a const
reference to the deduced type (a pointer), as if it were declared this way:
const Device *& ioDev = *i;
It seems needlessly complicated; if you need just normal iteration (and not e.g. manipulating the address of the pointer, which I think is highly unlikely), use a plain unmodified auto
:
for (auto ioDev : deviceList)
or an explicit type:
for (Device* ioDev : deviceList)
This is a range based for loop, it has the same basic behavior of:
for(auto it = deviceList.begin(); it != deviceList.end(); ++it) { const auto& ioDev = *it; }
The range based for loop has quickly become one of my favorite constructs, it's terse and when you need to iterate an entire range, works as well (and as efficiently) as possible.
If you need the other constructs of a typical for loop (say to exit early in some case), then range-based for isn't for that use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With