`c++17` ranged for loop over std::vectors with value and index

201 Views Asked by At

How can I have access to both value and index in a c++17 ranged for loop over std::vectors?

#include <vector>
#include <iostream>

int main()
{
    std::vector<double> v{4.1,5.2,0.11,0.34};
    for(auto &&[x, idx]: v)
        std::cout<<"v["<<idx<<"]: "<<x<<std::endl;
    return 0;
}

My code fails

main.cpp:7:13: error: cannot decompose non-array non-class type ‘double’
  for(auto &&[x, idx]: v)
             ^~~~~~~~

g++ -std=c++17 main.cpp -lstdc++

version:

gcc version 7.1.0 (Ubuntu 7.1.0-10ubuntu1~16.04.york0)

0

There are 0 best solutions below