This code does not work since auto & is a constant reference. [emphasis mine]
Your reasoning is not fulfilled. In a range-based loop, what you declare (here, auto& ab
) is not related to the range expression (here {a,b }
). Instead, ab
will be initialized from the elements of the range, not the range itself.
Instead, an error occurs when calling std::sort
with the parameters ab.begin()
/ ab.end()
, which is easy to testify by commenting on the body of the loop. As RMartinho pointed out, the std::initializer_list<std::vector<double>>
elements are immutable, and you cannot sort the const
container ( std::sort
shuffle the elements by moving, cannot assign the const
element).
Assuming you want to (independently) sort both vectors, you can do:
for(auto& ab: { std::ref(a), std::ref(b) }) std::sort(std::begin(ab.get()), std::end(ab.get()));
Note that in accordance with the rules for outputting template arguments auto&
here is good, and auto
will be displayed on const std::reference_wrapper<std::vector<double>>
, which gives std::reference_wrapper<std::vector<double>> const&
as type ab
.
source share