使用变量获取STL容器的size_type

Fab*_*ian 5 c++ loops auto

我想以简单的方式编写基于索引的 for 循环。由于我的代码必须在 32 位和 64 位中运行,因此我收到很多有关隐式转换的警告,因为我通常使用 32 位整数,但 STL 在 64 位中使用 64 位整数。

std::vector<MyClass> c;
for (FOO ui = 0, uiEnd = c.size(); ui < uiEnd; ++ui){...}
Run Code Online (Sandbox Code Playgroud)
  • FOO = unsigned int在 32 位上工作,但在 64 位上生成警告。
  • FOO = size_t适用于 32 和 64 位,但并不完全正确,因为标准不要求std::vector<MyClass>::size_type == size_t.
  • FOO = auto不起作用(这是非常不幸的),因为它单独设置每个变量的类型,因此文字 0 (或 0UL 或其他)的类型不同于 c.size() (在 32 位或 64 位中, c.size() 可能不同,所以我无法写出正确的文字)。
  • for (auto uiEnd = c.size(), ui = 0*uiEnd; ui < uiEnd; ++ui){...}其工作原理是用正确的类型表达 0,但比较晦涩。
  • FOO = decltype(c.size())有效,但我发现它很晦涩。
  • FOO = std::vector<MyClass>::size_type有效,但我发现重复容器的类型很乏味。

我更喜欢类似的东西FOO = c::size_type,它清楚地表达了正在发生的事情。但是是否可以仅使用变量size_type来获得?我尝试了以下方法但没有成功:std::vector<MyClass>c

  • c::size_type
  • typeid(c)::size_type
  • decltype(c)::size_type

Jar*_*d42 3

而你可能会使用:

std::vector<MyClass> c;

for (decltype(c)::size_type ui = 0, uiEnd = c.size(); ui < uiEnd; ++ui){...}
Run Code Online (Sandbox Code Playgroud)

我会用:

std::vector<MyClass> c;

std::size_t index = 0; // as you want index too
for (auto& myclass : c){...; ++index;}
Run Code Online (Sandbox Code Playgroud)

即使在 C++20 中:

std::vector<MyClass> c;

for (std::size_t index = 0; auto& myclass : c){...; ++index;}
Run Code Online (Sandbox Code Playgroud)

range-v3enumerate视图:

std::vector<MyClass> v;

for (const auto& [index, myclass] : v | ranges::v3::views::enumerate) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

演示