基于范围的循环忽略元素

时间:2018-05-11 16:41:15

标签: c++ c++11

我正在为自定义容器类型编写单元测试。我想确保它包含正确数量的元素。

int count = 0;
for (const auto &el : region) {
  ++count;
}
// Check that count is the right number

因为这段代码对'el'没有任何作用,所以我得到一个关于未使用变量的编译器警告。如何编写基于范围的for循环而不声明像'el'这样的“变量别名”?

显式使用迭代器的老式for循环显然会解决这个问题,但我只是想知道是否可以使用基于范围的for来完成。

1 个答案:

答案 0 :(得分:4)

至少有两种方法可以取消警告:

for ([[maybe_unused]] const auto &el : region) // C++17 or newer
{
    // ...
}

for (const auto &el : region)
{
    (void)el;
    // ...
}

但正如@ Jarod42的评论中所指出的,如果你的容器有适当的迭代器,你可以使用std::distance(std::begin(region), std::end(region));代替。