tags:

views:

80

answers:

3

Hi,

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;
+2  A: 

Well, you don't need a loop to use iterators:

vector<Desempenho>::const_reverse_iterator rit = v_2.rbegin();
if (rit != v_2.rend()) {
    ultimo = rit->maximo;
    if (++rit != v_2.rend()) {
        penultimo = rit->maximo;
        if (++rit != v_2.rend()) antepenultimo = rit->maximo;
    }
}

If you want to be needlessly flashy:

size_t len = v_2.size();
switch(len) {
    default:
        antepenultimo = v_2[len-3].maximo;
    case 2:
        penultimo = v_2[len-2].maximo;
    case 1:
        ultimo = v_2[len-1].maximo;
    case 0:
        break;
}

But your code reviewer will throw a biro at your head. More sensibly, a single error-check might do:

size_t len = v_2.size();
if (len >= 3) {
    ultimo = v_2[len-1].maximo;
    penultimo = v_2[len-2].maximo;
    antepenultimo = v_2[len-3].maximo;
}
Steve Jessop
+1  A: 

You can get the size via the size() method and then output with something like this.

cout << v_2.at(size-1) << v_2.at(size-2) << v_2.at(size-3)

If size is the result from the size() method.

Ólafur Waage
This throws an exception if the vector is too small, whereas the original code prints a default-initialized object. Or in this example, an uninitialized object, but I was assuming that's an accident :-)
Steve Jessop
Aye true, but that could be overcome quite simply.
Ólafur Waage
+1  A: 

The simplest that comes to mind is 3 assigments. However, you can do something funky like this:

int ultimo = 0, penultimo = 0, antepenultimo = 0;
int* ptr[3] = {&ultimo, &penultimo, &antepenultimo};
for (int i = 2; i >= 0; i--)
    if (v_2.size() - i >= 0)
        *ptr[i] = v_2[i];
Leonid
Very interesting. That would be a good technique if you had, say, 100 different variables.
Alexander Rafferty