I’d like to place the last three values of vector v_2 in three variables (one value per variable).
Is there a faster or simpler way to do this?
struct Desempenho {
double maximo;
};
double ultimo, penultimo, antepenultimo;
Desempenho d;
int n (0);
vector<Desempenho> v_2;
d.maximo=1.1;
v_2.push_back(d);
d.maximo=2.2;
v_2.push_back(d);
d.maximo=3.3;
v_2.push_back(d);
d.maximo=4.4;
v_2.push_back(d);
d.maximo=5.5;
v_2.push_back(d);
for (vector<Desempenho>::const_reverse_iterator rit = v_2.rbegin(); rit != v_2.rend(); ++rit) {
cout << "XXXX " << n << endl;
if (n==0) ultimo = rit->maximo;
else if (n==1) penultimo = rit->maximo;
else if (n==2) antepenultimo = rit->maximo;
else break;
++n;
}
cout << ultimo << " " << penultimo << " " << antepenultimo < < endl;
Well, you don’t need a loop to use iterators:
If you want to be needlessly flashy:
But your code reviewer will throw a biro at your head. More sensibly, a single error-check might do: