user6800688 user6800688 - 3 months ago 7
C++ Question

How can I add two values in a list in C++ using rbegin() and advance(iterator,1)?

I'm trying to calculate the fibonacci series using a list in C++, as instructed.
I was left with notes on how to improve it, and I simply don't understand what is being asked of me. How can i use rbegin() and advance(iterator,1) to add previous values and calculate a new one?

Here is what I had earlier.

list mutableFibonacci(int position)
{

list<int> series;
int first = 0; //Remove
int second = 1; //Remove

for (int i = 1; i <= position; i++)
{
if (i == 1)
series.push_back(1);
else
{
//We can get the last value and the value before from the series, like so, series.rbegin(); then get the value from the reverse iterator. Then we can call advance(iterator, 1) to get to the previous value. We can get the second to last value.
series.push_back(first + second);
first = second;
second = series.back();

}
}
return series;


}

Here is what I tried to do to fix it.

for (int i = 1; i <= position; i++)
{
if (i == 1)
series.push_back(1);
else
{


int last = series.rbegin();
int previous = advance(series, 1);
series.push_back(last + previous);
}
}
return series;

Answer
 series.push_back(1);
 series.push_back(1);

 for (int i = 3; i <= position; ++i){                     //First 2 elements inititalised
    list<int>::reverse_iterator it = series.rbegin();     //End of the list
    list<int>::reverse_iterator it2 = it;                 //Copy the iterator
    advance(it2,1);                                       //Move the iterator
    series.push_back(*(it)+*(it2));                       //Add the sum
}

Without the int it can look like this. The auto from before is a C++11 shortcut to defining types for variables (thus instead of having to type list<int>::reverse_iterator I can type auto)