在循环中使用自动 C++ [英] Using auto in loops c++

查看:35
本文介绍了在循环中使用自动 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下代码的签名/未签名不匹配警告:

I get warning signed/unsigned mismatch for the following code:

auto n = a.size();
for (auto i = 0; i < n; i++) {
}

问题在于,通过将 0 分配给 i,它变成了 int 而不是 size_t.那么什么更好:

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++) {
}

或者这个:

auto n = a.size();
for (size_t i = 0; i < n; i++) {
}

或者您有更好的解决方案?我更喜欢第一个因为它更加一致,它只使用 size_t 而不是 size_tauto出于同样的目的.

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.

推荐答案

基于范围的循环可能是更简洁的解决方案:

A range based loop could be a cleaner solution:

for (const auto& i : a)
{

}

这里,i 是对容器a 元素的const 引用.

Here, i is a const reference to an element of container a.

否则,如果需要索引,或者不想遍历整个范围,则可以使用 decltype(a.size()) 获取类型.

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) {
}

这篇关于在循环中使用自动 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆