Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using auto in loops c++

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.

like image 660
user2381422 Avatar asked Jul 06 '13 17:07

user2381422


People also ask

What does auto do in a for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression.

How do you use a range-based loop?

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() .

What is ranged for loop?

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.

How do I repeat a loop in C?

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.


2 Answers

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) { } 
like image 194
juanchopanza Avatar answered Oct 02 '22 14:10

juanchopanza


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.

like image 36
SomeWittyUsername Avatar answered Oct 02 '22 14:10

SomeWittyUsername