Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - Forcing auto to be a reference type in a range for loop

Suppose I have foo which is a populated std::vector<double>.

I need to operate on the elements of this vector. I'm motivated to write

for (auto it : foo){
   /*ToDo - Operate on 'it'*/
}

But it appears that this will not write back to foo since it is a value type: a deep copy of the vector element has been taken.

Can I give some guidance to auto to make it a reference type? Then I could operate directly on it.

I suspect I'm missing some trivial syntax.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

A minimal auto reference

The loop can be declared as follows:

for (auto& it : foo) {
   //    ^ the additional & is needed
   /*ToDo - Operate on 'it'*/
}

This will allow it to be a reference to each element in foo.

There is some debate as to the "canonical form" of these loops, but the auto& should do the trick in this case.

General auto reference

In a more general sense (outside the specifics of the container), the following loop works (and may well be preferable).

for (auto&& it : container) {
   //    ^ && used here
}

The auto&& allows for bindings to lvalues and rvalues. When used in a generic or general (e.g. template situation) this form may strike the desired balance (i.e. references, copies, prvalue/xvalue returns (e.g. proxy objects) etc.).

Favour the general auto&&, but if you have to be specific about the form, then use a more specific variation (e.g. auto, auto const& etc.).

Why is auto&& better?

As noted in other answers here and the comments. Why is auto&& better? Simply it will do what you think it should in most cases, see this proposal and its update.

As always, Scott Meyers' blog about this also makes for a good read.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...