I get warning signed/unsigned mismatch for the following code:
auto n = a.size(); for (auto i = 0; i < n; i++) { }
The problem is that by assigning 0 to i
it becomes int
rather than size_t
. So what is better:
size_t n = a.size(); for (size_t i = 0; i < n; i++) { }
or this:
auto n = a.size(); for (size_t i = 0; i < n; i++) { }
or maybe you have a better solution? I like the first one more because it is bit more consistent, it just uses size_t
rather than both size_t
and auto
for the same purpose.
Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression.
Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .
Example 1: Ranged for Loop Using Array Note: The ranged for loop automatically iterates the array from its beginning to its end. We do not need to specify the number of iterations in the loop.
Syntax. The basic syntax for a repeat / until loop looks like this: repeat DoSomething(); DoSomethingElse(); until x ≥ 10; where a conditional expression is specified after the closing until keyword, and a list of statements can be provided between the repeat and until keywords.
A range based loop could be a cleaner solution:
for (const auto& i : a) { }
Here, i
is a const
reference to an element of container a
.
Otherwise, if you need the index, or if you don't want to loop over the entire range, you can get the type with decltype(a.size())
.
for (decltype(a.size()) i = 0; i < a.size(); ++i) { }
Depending on what you want to do inside the loop and the capabilities of your compiler, range-based for loop might be a better solution.
All of your presented solutions are not bad in most situations, with minor differences Your first solution is actually worse choice and that's exactly what your compiler tells you. Second solution is better but if you want to avoid directly defining types for simplicity or some future changes, you can do the following:
auto n = a.size(); for (decltype(n) i = 0; i < n; i++) { }
This way you bind the i
and n
types to always match each other.
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