I have written a C program to find fibonacci numbers. It's running successfully but is not printing anything.
#include<bits/stdc .h>
using namespace std;
int main(){
int n = 5;
vector<int> fib;
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i ){
fib[i] = fib[i-1] fib[i-2];
}
cout<<fib[n];
}
If I do the same thing using array instead of vector it prints successfully.
#include<bits/stdc .h>
using namespace std;
int main(){
int n = 5;
int fib[10];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i ){
fib[i] = fib[i-1] fib[i-2];
}
cout<<fib[n];
}
I have tested this on sublime text and onlinegdb.
CodePudding user response:
int fib[10];
This creates an array of 10 integers.
vector<int> fib;
This creates a vector of size 0, with 0 integers.
For these two snippets to match, you need to initialize the vector with 10 integers like the array. So:
vector<int> fib(10);
Some notes on vectors
One of the big differences between std::vector
and primitive arrays is that std::vector
is resizable! So while initializing the vector with 10 ints like above will work, you could also add them on the fly using push_back()
or by calling resize()
.
Likewise, std::vector
has a .at()
function for access. It's marginally slower than the subscript operator ([]
), so I would not suggest using it in production-level code. But while you're learning, I would strongly suggest using .at()
, as it will do bounds checking for you. So this program would've told you you were trying to access locations in the vector that don't exist--instead of just running with Undefined Behavior.
CodePudding user response:
Note that when you wrote :
vector<int> fib;//creates an empty vector that is a vector of size 0
fib[0] = 0; //UNDEFINED BEHAVIOR
fib[1] = 1; //UNDEFINED BEHAVIOR
In the above code snippet, you created an empty std::vector
. That is a vector of size 0
.
Next when you wrote fib[0] = 0;
you're trying access the first element of the vector. That is, the element at index 0
. But note that there is no element inside the vector and so you have undefined behavior in your program.
Similarly when you wrote fib[1] = 1;
, you're trying to access the second element of the vector. But since there is no element inside the vector, this again leads to undefined behavior.
To solve this you can create a vector of some size(say 10) and then access its elements as shown below:
vector<int> fib(10);//create vector of size 10
fib[0] = 0;//OK NOW
fib[1] = 1;//OK NOW
Since you're using indices to access the elements of the vector, i have not suggested push_back
. std::vector::push_back
is a member function that can be used to add an element into the vector.