-1

I need to add two types int and auto to the loop. But maybe I want to add a couple more types. Maybe I can use lambda.

I need the best way to implement this.

for(int i, auto h; i < 10; i++)
{                             }
user
  • 43
  • 6

2 Answers2

2

You can use std::pair

like this:

#include <iostream>
#include <string>
#include <utility>

int main()
{
    for(std::pair<int,std::string> p = std::make_pair(0,"X"); p.first <10 ; p.first ++)
    {
        std::cout<<p.second<<std::endl;
    }
    return 0;
}
SHR
  • 7,149
  • 9
  • 32
  • 50
1

No, you can't declare multiple types in the for loop initialiser.

Bearing in mind that you can initialise them, a reasonable alternative is

{
    Foo h;
    for (int i = 0, h = Foo(); i < 10; ++i){
    }
}

where the outer braces stop h from leaking into the surrounding scope. Another idea would be to use a std::tuple or similar.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451