Forcing auto to be a reference type in a range for loop

后端 未结 4 1088
春和景丽
春和景丽 2020-12-17 09:29

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

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

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 09:52

    In many ways this confusion is arising from the convention that's grown up over the years to bind a * or a & to the type as opposed to the variable.

    For example int* a is really int *a; i.e. a is a pointer to a value of type int.

    The same applies to references: in the case of int& a, a is a reference to a value of type int.

    So what you really want to do is write for (auto &it : foo) so it is a reference to the type inferred by auto. Then you can use it to manipulate the underlying vector elements. More often than not this will be written as

    for (auto& it : foo)

    Moving forward, you might want to use an r-value reference: for (auto&& it : foo) which is probably the best general form.

提交回复
热议问题