Programs & Examples
References: lvalue and rvalue · Study material
Normalize a vector in place through a reference
The function receives the vector by reference and rewrites every element through double&; std::minmax_element finds both ends of the range in one pass.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
void normalize(std::vector<double>& v) { // modifies the caller's vector
auto [lo, hi] = std::minmax_element(v.begin(), v.end());
double min = *lo, range = *hi - *lo;
for (double& x : v) x = (x - min) / range * 100;
}
int main() {
std::vector<double> scores{40, 55, 70, 85, 100};
normalize(scores);
std::cout << std::fixed << std::setprecision(1);
for (double s : scores) std::cout << s << ' ';
std::cout << '\n';
return 0;
}
0.0 25.0 50.0 75.0 100.0
Overloads that detect temporaries
The lvalue/rvalue overload set from the introduction is the same mechanism a class uses to choose between its copy constructor (const T&) and move constructor (T&&).
Counting through std::ref in a thread
std::thread copies its arguments; wrapping the counter in std::ref passes a reference instead, so the thread updates the caller's variable (see the std::ref example above).