Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

iteration - How to iterate over non-const variables in C++?

#include <initializer_list>

struct Obj {
    int i;
};

Obj a, b;

int main() {
    for(Obj& obj : {a, b}) {
        obj.i = 123;   
    }
}

This code does not compile because the values from the initializer_list {a, b} are taken as const Obj&, and cannot be bound to the non-const reference obj.

Is there a simple way to make a similar construct work, i.e. iterate over values that are in different variables, like a and b here.

question from:https://stackoverflow.com/questions/57215858/how-to-iterate-over-non-const-variables-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It does not work because in {a,b} you are making a copy of a and b. One possible solution would be to make the loop variable a pointer, taking the addresses of a and b:

#include <initializer_list>

struct Obj {
    int i;
};

Obj a, b;

int main() {
    for(auto obj : {&a, &b}) {
        obj->i = 123;   
    }
}

See it live

Note: it is generically better to use auto, as it could avoid silent implicit conversions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...