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.
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.
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.
Related
I have int arr[10] and I want the change the array size manually to be 5
I tried:
int arr[10];
for (int i = 0; i < 10; i++)
{
arr[i] = i + 1;
}
arr[5] = nullptr;
But this didn't work and the array size still 10.
Arrays have a fixed size. One of the many reasons you should be using a vector instead. It's easy to change the size of a vector.
Like this
#include <vector>
std::vector<int> arr(10); // vector has size 10, note use (10) not [10]
for (int i = 0; i < arr.size(); i++) // use size() to get the vector's size
{
arr[i] = i + 1;
}
arr.resize(5); // change the vector's size to 5
An array's size is static in C++.
You should use vectors instead.
Please see: How to resize array in C++?
You can't change the size of the array that is not declared dynamically I think.
what you can do is declare a new array of size 5 and copy the contents over to the newly declared array.
Or if you don't want that headache, just use vectors.
I am a newbie in cpp field.
Below is my cpp code. When I use the online c++ compiler, and
why does it happened to exited, segmentation fault, and what's wrong with my code.
Thanks guys.
Problem description:
Given an array of integers arr, you’re asked to calculate for each index i the product of all integers except the integer at that index (i.e. except arr[i]). Implement a function arrayOfArrayProducts that takes an array of integers and returns an array of the products.
Solve without using division and analyze your solution’s time and space complexities.
#include <iostream>
#include <vector>
using namespace std;
vector<long> arrayOfArrayProducts(const vector<int>& arr)
{
vector<long> res = {};
int n = arr.size();
// handles edge cases as well
if(n==0 || n==1){
return res;
}
int product;
// your code goes here
for(int i=0; i<n; i++){
product = 1;
for(int j=0; j<n; j++){
if(i!=j){
product = arr[j]*product;
}
res[i]=product;
}
}
return res;
}
int main() {
// vector initiallize
//vector<int> arr{8, 10, 2};
const vector<int> arr;
int n = arr.size();
vector<long> ans(n,0);
ans = arrayOfArrayProducts(arr);
for(int i=0; i<n; i++){
cout<< ans[i] <<' ';
}
return 0;
}
Here is the line where the failure comes:
res[i] = product;
and the reason is because you declared res like this:
vector<long> res = {};
so you are trying to access the long element located at 'cell' i of an empty vector... that is not allowed in C++ and the result is undefined behavior
fix it:
the same way as in the main function
std::vector<long> arrayOfArrayProducts(const std::vector<int>& arr)
{
int n = arr.size();
std::vector<long> res(n, 0);
....
Segmentation faults typically occur when you try to read past the bounds of an array. This fault in your code means that you're trying to read/ write something from an array which is not allocated. If you take a closer look, res[i]=product means that your accessing elements from the vector res. But you haven't reallocated or inserted data into it. This is the reason for the segmentation fault.
To resolve this, resize the res vector to the size of arr so that the vector will have the elements in memory to be accessed,
vector<long> arrayOfArrayProducts(const vector<int>& arr)
{
vector<long> res(srr.size());
...
You are getting this error because you are trying to access the index i of the vector<int> res that you never initialized. on this line:
res[i] = product;
For that you have to understand how Vector works, Vector is dynamic container which can shrink and expand based on its usage, in your case, You Initialized it with default constructor, which did not allocated any memory to hold int. So when you try to access that you get undefined behavior.
In case of default construction of vector. You cannot assign to a particular index. but you have can put data in it via this:
res.push_back(data);
You can fix it by using these constructors:
std::vector<int> res(arr.size(), 0); // In second parameter you can pass default values for all the elements in the vector.
std::vector<int> res(arr.size()); //This will simply initialize elements with default constructor
This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 3 years ago.
This is my code and it works. For example, when n=5, it returns 5. Since n=5, and defining arr[0] = 0, isn't there only four more spaces left to store the elements from arr[1] to arr[4]?
However, it seems like 6 elements(from arr[0] to arr[5]) could be stored and I do not know how.
int fibonacci(int n) {
int i;
int arr[n];
arr[0] = 0;
for(i=1; i<=n; i++)
{
if(i==1)
{
arr[i] = 1;
}
else
{
arr[i] = arr[i-2] + arr[i-1];
}
}
return arr[n];
}
This is undefined behaviour.
Behind the scenes
What's going on behind the scenes is that 5 ints are allocated on the stack. Lets say they're put at address 0x20 to 0x30. The array notation [] is really syntax sugar for using pointers. This means that arr[0] really is a pointer to 0x20. Your array in this case translates to the following addresses (because sizeof(int) = 4):
arr[0] = (arr+0) = 0x20
arr[1] = (arr+1) = 0x24
arr[2] = (arr+2) = 0x28
arr[3] = (arr+3) = 0x2C
arr[4] = (arr+4) = 0x30
This is all fine and good, you're operating on allocated memory. What happens when you try to write to index 5? Well, the same thing, basically:
arr[5]= (arr+5) = 0x34.
It's still just a pointer to an address that you want to write to. The problem is, however, that you haven't told anyone that you intend to write to that address - the memory has not been set aside for you.
If it has not been set aside for anything else, this will likely turn out alright - as you observe.
However if it has it can turn into all sorts of strange behavior depending on what it was used for. Maybe it has been set aside and is just not used yet, maybe it has been used but is simply overwritten and will not be checked again. The point is we don't know! Therefore it is dangerous and undefined.
The reason why it even works in the first place, is that - again - it is just dereferencing a pointer. And dereferencing a pointer should work, as you're trusted to know more that the compiler. It may warn you that you probably shouldn't do this, but it's not an error per se.
What you should do instead
When working with variable length arrays in C++, one should use the modern tools available since C++11. In this scenario, it's advisable to use std::vector instead. If you use the at function rather than [] it checks whether the index is inside the bounds.
Its unexpected behavior, even warn by C++ documents, maybe they removed out-boundary checking. Not only that, you even assign to it. So better to be under range.
#include <iostream>
using namespace std;
int main(){
int i, n = 5;
int arr[n];
arr[0] = 0;
arr[1] = 1;
for(i=2; i<n; i++){
arr[i] = arr[i-2] + arr[i-1];
}
arr[8]=99; //assigning out of range
//accessing out of range
for(i=0;i<20;i++){
cout<<arr[i]<<" ";
}
}
#OUT: 0 1 1 2 3 0 211951624 1 99 32766 -484579280 32766 -1740650656 32767 -484579408 32766 5 0 5 0
You are facing issues with the int array. int arr[n]; is not valid C++ code if n is not fix at compile time. You can rewrite your code with the help of std::vector as
int fibonacci(int n) {
std::vector<int> arr(n);
arr[0] = 0;
for(int i=1; i<=n; i++)
{
if(i==1)
{
arr[i] = 1;
}
else
{
arr[i] = arr[i-2] + arr[i-1];
}
}
return arr[n];
}
Comments:
Your code will use a lot of memory for large Fibonacci numbers, since you store the entire series. This is superfluous, since only have to store the last two entries of the Fibonacci series.
You don't have to loop over n in order to calculate the Fibonacci number. The Moivre-Binet formula gives a much quicker way of calculating these.
for(i=1; i<=n; i++)
the for loop wil run if i is less than or equal to n, which means that when n = 5, it will still run.
I'm learning C++ (reasonably confident in JavaScript) and I can't find a C++ equivalent to the JS array.length;. I want a simple way to loop through an array based on the array length?
I have followed a number of tutorials but all seam to require the array length to be manually stated in the for loop (or pushed into the function)?
Below code gets an error and adding the #include causes a compiler error (DEV++).
Is there a C++ or reason why there is no simple call of the array length?
#include <iostream>
using namespace std;
int main () {
int shoppingList [3] = {1, 2, 3};
for (int i=0; i < shoppingList.size(); i++) {
cout << shoppingList[i] << endl;
}
}
For a C-style array like you have you can use range-based for loops:
for (int value : shoppingList)
{
std::cout << value << '\n';
}
As for getting the number of elements from an array, there's a "trick": You know the size of the array itself, and you know the size of each element in the array. That means if you divide the size of the array with the size of each element, you will get the number of elements.
In short
size_t numberElements = sizeof shoppingList / sizeof shoppingList[0];
Important note: This "trick" only works with actual arrays! Once an array have decayed to a pointer (to its first element, which often happens) all you're left with is the pointer. There's no way to get the size of the memory it points to, and this "trick" can not be used.
And as mentioned in my comment, the "best" solution is to use either std::array or std::vector.
Built-in types don’t have member functions with C++. However, there is a non-member std::size(array) function:
for (std::size_t i{}; i != std::size(shoppingList); ++i) {
// ...
}
Note that the counter is usinf std::size_t to match the signedness of the result of std::size(...). Also, do not use the sizeof hack suggested in other answers: it is a trap! The cde will happily compile when passing pointers to it but it will also produce the wrong result.
Of course, the idiomatic way to iterate over a range in C++, including arrays, is (assuming you only need the values and not their position):
for (int val: shoppingList) {
// ...
}
Array doesn't have a direct size() member function, you can find the size of an array like this int size = sizeof(arr)/sizeof(arr[0]); and use it in the for loop.
#include <iostream>
using namespace std;
int main () {
int shoppingList [3] = {1, 2, 3};
int size = sizeof(shoppingList)/sizeof(shoppingList[0]);
for (int i=0; i < size(); i++) {
cout << shoppingList[i] << endl;
}
}
You can do something like, sizeof(A)/sizeof(A[0]). This would give you the total number of elements in the array.
Let's take an example A = {1,2,3,4,5} // all ints
If you evaluate sizeof(A)/sizeof(A[0]), it would give you 5 and as you see, you would not need to manually enter the size of the array.
Hope this helps. :)
#include <iostream>
using namespace std;
int main()
{
A = {1,2,3,4,5};
for (int i = 0; i< sizeof(A)/sizeof(A[0]); i++)
//whatever you want to do with this
return 1;
}
i have created a map called select_p and vector of this map is called pts. i have stored data in a array and i want to pushbcak these data into my vector of map. i tried this by inserting value of array into new vector and then pushback into my map.but it is not working please help me to correct these codes? thanks
#include<iostream>
#include<cstdlib>
#include <map>
#include <vector>
using namespace std;
int main()
{
int M=7;
int N=6;
int i=0;
int * temp;
map<int,vector<int> > select_p;
vector<int>pts;
for (int m=0; m<M; m++)
{
for (int n=0; n<N; n++)
{
vector<int>id;
if (n==0 && m==5)
{
temp = new int[3,i+N,i+N+1,i+1];
unsigned ArraySize = sizeof(temp) / sizeof(int);
id.insert(id.begin(),temp[0], temp[ArraySize]);
select_p[i].push_back(id);
}
i++;
}
}
delete[] temp;
system("PAUSE");
return 0;
}
for (int m=0; m<M; m++) {
for (int n=0; n<N; n++) {
if (n==0 && m==5) {
Why are you looping when you only actually do anything for a single pair of values of m and n? The loops are completely useless here; you would get the same effect by just setting n = 0 and m = 5.
temp = new int[3,i+N,i+N+1,i+1];
Whatever you think this does, that's not what it does. This is equivalent to temp = new int[i+1];. The rest of the expression inside of the [] has no effect.
That said, you should not use new to create arrays in your program. Use std::vector; it is far easier to use correctly.
unsigned ArraySize = sizeof(temp) / sizeof(int);
This does not work. When you dynamically allocate an array, you are responsible for keeping track of how many elements are in it. Given a pointer to a dynamically allocated array (like temp here) there is no way to determine the number of elements in the array.
What you have is equivalent to sizeof(int*) / sizeof(int), which is not going to do what you expect.
id.insert(id.begin(),temp[0], temp[ArraySize]);
std::vector::insert takes a range of iterators: you have provided it with two values. Presumably you want to use temp, which points to the initial element of the dynamically allocated array, and temp + i + 1, which points one past the end of the array. That said, since you haven't set the values of the elements in the array, you are copying uninitialized memory, which probably isn't what you mean to do.
select_p[i].push_back(id);
select_p[i] is a std::vector<int>. std::vector<int>::push_back() takes a single int that is appended to the sequence. Presumably you just mean to use assignment to assign id to select_p[i].
You should get a good introductory C++ book if you want to learn to program in C++. I am sorry to say that your program is nonsensical.