使用auto在循环c ++ [英] Using auto in loops c++

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

问题描述

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

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

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

问题是,通过将 i 赋值为 int ,而不是
那么什么更好:

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_t

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 const 对容器 a 的元素的引用。

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

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

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