Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range based for loop through non-const literal c++

Compiler context: I am compiling with GDB v8.3 Ubuntu with options g++ -Im -O2 -std=c++0x.

Very frequently I need to complete some loop for two or three objects so I use wrap the expression in a range based for loop with a containing litteral.

In Python3 this would look like:

a = [1,2,3]
b = [4,5,6]

for v in (a,b):
    func(v)

In c++ this obviously isn't so simple. As far as I am aware, using {a,b} creates some type of initializer list, therefor casting does not properly work. In my attempts I come to something of this sort, but do no understand how I would properly pass by reference and also have it be mutable, as my compiler complains this is neccessarily const.

vector<int> a {1,2,3};
vector<int> b {4,5,6};

for(auto& v: {a,b}) // error non-const
    func(v);
like image 320
Hunter Kohler Avatar asked Oct 13 '25 00:10

Hunter Kohler


1 Answers

Based on your python program, it appears that you want to iterate through all the vectors, but with a mutable reference to each vector. You can do this by using pointers:

for(auto *v: {&a, &b})  // iterate over pointers to the vectors
    func(*v);           // dereference the pointers to get mutable
                        // references to the vectors 

Here's a demo.

like image 133
cigien Avatar answered Oct 14 '25 12:10

cigien