El3ctroGh0st El3ctroGh0st - 1 month ago 18
C++ Question

Fibonacci Sequence with vectors

I'm currently trying to solve some problems of the Euler-Projects, but I'm currently stuck at the second problem. Here is what I have right now:

void p002()
{
unsigned int result = 0;
std::vector<int> fibonacci{ 1,2 };

for (int i = 2; fibonacci.at(i) < 4000000; i++)
{
fibonacci.at(i) = fibonacci.at(i - 1) + fibonacci.at(i - 2); //<- Doesn't work
if (fibonacci.at(i) % 2 == 0)
result += fibonacci.at(i);
}

std::cout << result;
}


Could someone help me out and tell me why this one line doesn't seem to work? (I get an "abort() called" error when trying to execute the code.)

In case anyone wonders: The task is to get the sum of all integers of the fibonacci sequence with a lower value than 4,000,000 which are even-valued.

Thanks!

Answer

vector::at throws an exception if you try to access an element at an index that is out of bounds. Your vector contains 2 elements (at indices 0 and 1). Therefore fibonacci.at(2) is out of bounds, and an exception is thrown. You don't catch the exception, so std::terminate is called. By default, std::terminate points to abort which terminates your process.

Solution: Add enough elements into the vector so that fibonacci.at(i) isn't out of bounds.