I am a newbie in C++. I am trying to write a C++ program that generates Fibonacci series by effective use of recursion. The program I have written is as follows -
#include<iostream>
#include<vector>
class FibonacciDynamic
{
private:
static std::vector<int> memo(index);
int index;
public:
FibonacciDynamic(int a);
int fib(int a);
void display();
};
FibonacciDynamic::FibonacciDynamic(int a)
{
index = a;
}
int FibonacciDynamic::fib(int a)
{
if (a <= 2)
{
return 1;
}
else if(memo.at(a-1) != 0)
{
return memo.at(a-1);
}
else
{
memo.at(a-1) = memo[a - 2] + memo[a - 3];
return memo.at(a-1);
}
}
void FibonacciDynamic::display()
{
for (int i = 0; i < index; i++)
{
std::cout << "Generating Fibonacci series..." <<std::endl;
std::cout << fib(i) << std::endl;
}
}
int main()
{
std::cout << "Please, enter the index" << std::endl;
int a;
std::cin >> a;
FibonacciDynamic f(a);
f.display();
return 0;
}
But, after compiling the code I am getting following errors -
error C2061: syntax error : identifier 'index'
error C2228: left of '.at' must have class/struct/union
error C2109: subscript requires array or pointer type
As all the errors are related with static vector that I've used, I think I have not declared it correctly; that's why compiler is not accepting it as vector & giving errors above. So, please help & guide me to correct way of vector usage in above code. Thanks.
static std::vector<int> memo(index);
That declares a static member function memo taking a single (unnamed) argument of type index and returning a std::vector<int>.
static std::vector<int> memo(index);
int index;
I don't know what you expect that to do, but since index is not initialized, you certainly cannot use it to initialize memo. What you have here will actually declare a static function (which I doubt is your intention).
Using a static vector for this is probably not the best route to take. If you are looking to find the Nth number in the Fibonacci sequence, you can use a vector member variable to store the intermediary values, or simply compute it each time.
Related
I'm using a set of objects in C++ to get log(n) times for inserting and finding.
In the code below I'm able to insert elements and make them ordered by x attribute, however, I'm not able to use lower_bound to find the lower bounds based on the same attribute. I don't know how to fix that. Any help will be appreciated.
Most of the examples on sets that I could find were not about a set of objects
struct MyObject {
float x = 0;
float y = 0;
const bool operator < ( const MyObject &r ) const{
return ( x< r.x);
}
};
set<MyObject> nset;
int main(){
MyObject n1;
n1.x=5;
n1.y=1;
MyObject n2;
n2.x=3;
n2.y=2;
nset.insert(n1);
nset.insert(n2);
// this works, the elementes are sorted according to x
for(auto elem: nset){
cout << elem.x << endl;
}
// this doesn't work
set<MyObject>::iterator it = lower_bound(nset.begin(), nset.end(), 1.2);
cout << it->x << endl;
//neither this one
// set<MyObject>::iterator it = nset.lower_bound(1.2);
// cout << it->x << endl;
cout << "hello" << endl;
return 0;
}
I want the lower bound function to point me to the lower bound "x" in the set of objects but the code fails to compile. Compiler error to the first lower bound says: Invalid operands to binary expression ('const MyObject' and 'double')
Compiler error to the second lower bound says: No matching member function for call to 'lower_bound'
EDIT: while the answer provided by user: 1201ProgramAlarm was quite helpful for me to understand and fix the error. I still think it is more convenient in my case to have a lower_bound function that accepts floats rather than objects. So I have implemented the following function to help me achieve that. Copied below just in case others were interested:
set<MyObject>::iterator mylower_bound(set<MyObject> &myset, float val){
MyObject f;
f.x = val;
set<MyObject>::iterator it = myset.lower_bound(f);
return it;
}
nset stores MyObject objects, and lower_bound needs one of the thing stored in the set. You're passing it 1.2, which is a double, but there is no way to construct a MyObject from a double. Thus the compilation failure.
You'll need to pass a MyObject to nset.lower_bound to do your search.
How am I supposed to pass static 2d array to function in cpp as an argument? I tried something like that:
void foo(int (&tab)[N][N]) {
// function body
}
int main() {
int n;
cin >> n;
int tab[n][n];
foo(tab); // doesn't work
return 0;
}
I get "no matching function error" when I try to call foo.
I need static arrays, because vectors are too slow for my needs. I would like to avoid declaring array with 10000 rows and columns, too. Moreover, I would want to use functions, because it will make my code readable. Is there any solution for this problem which will meet my expectations?
With cin >> n;int tab[n][n];, you declare a variable length array (i.e. an array which's dimensions are not compile-time-constants).
You have two problems here: First, they are not supported by standard C++, and second they are not compatible with fixed size array parameters you introduced.
If you declare your array with compile time known size, however, it will work:
#define N 10
void foo(int (&tab)[N][N]) {
cout << tab[1][1] << endl;
}
int main() {
int tab[N][N] = {};
tab[1][1]=15;
foo(tab);
return 0;
}
The classical C++ solution would involve using vectors of vectors. If it's not suitable (because you want more speed or more control over memory), you can define your own class for a square 2-D array.
One idea I used in my code is, implement it using an underlying 1-D vector, with accessor method returning a pointer.
struct My_2D_Array
{
explicit My_2D_Array(size_t n):
m_size(n),
m_data(n * n)
{
}
int* operator[](size_t i)
{
return m_data.data() + i * m_size;
}
size_t m_size;
std::vector<int> m_data;
};
This not only lacks all sanity checks, and also makes bound-checked access impossible (because the accessor returns a bare pointer), but will work as a quick-and-dirty solution.
Usage in your code:
int foo(My_2D_Array& matrix)
{
// example
return matrix[2][3] + matrix[3][2];
}
int main()
{
int n;
cin >> n;
My_2D_Array tab(n);
foo(tab);
return 0;
}
This idea is highly customizable - you can make the code for My_2D_Array as simple or as clever as you want. For example, if you still don't like usage of vector, even though it's 1-D, you can manage (allocate/deallocate) your memory separately, and store int*, instead of vector<int>, in My_2D_Array.
Just use a vector<> of vector<int>. No need for mucking around with non-standard arrays.
I have written the following code but it is showing the error
use of parameter outside function body before ‘]’ token
The code is
#include <iostream>
using namespace std;
int n=10;
void a(int s[n][n])
{
cout<<"1";
}
int main()
{
int s[n][n]={0};
a(s);
}
I am trying to pass a multidimensional array of variable size using global variable. I don't want to use vectors in this.
Firstly C++ doesn't have variable-length arrays, So Instead of int s[n][n]={0}; you should use
std::vector<std::vector<int>> s(10,std::vector<int>(10));
Secondly how to pas 2D array to a function,
void a(std::vector<int> **s,int rows, int cols){
cout<<"1";
/* stuff with 2D array */
}
You've already received answers which explain the why. I'm offering this only as a matter of completeness to C++. Personally, though I don't understand why you're avoiding vectors, they do offer a more intuitive or pleasing solution. Inside of your function for handling the vectors, you can always consult std::vector<>.size() to ensure you stay within bounds or std::vector<>.at() and catch the exception that is thrown when accessing out of bounds. Nevertheless, your particular question may also be solved by templates. Below is your code, slightly modified, with comments to illustrate. I tested using gcc 4.8.5:
#include <iostream>
using namespace std;
// Made constant so that the compiler will not complain
// that a non-constant value, at compile time, is being
// used to specify array size.
const int n=10;
// Function template. Please note, however, this template
// will only auto-gen functions for 2D arrays.
template<int lb>
void a(int s[][lb])
{
// output the last element to know we're doing this correctly
// also note that the use of 9 hard-codes this function template
// to 2D arrays where the first dimension is always, at least, 10
// elements long!!!!!!
cout << s[9][lb - 1] << endl;
}
int main()
{
int s[n][1];
s[9][0] = 15;
a<1>(s); // explicitly call template with the size of the last dimension
a(s); // Call the same function generated from the previous call
int t[n][2];
t[9][1] = 17;
a(t); // compiler implicitly determines the type of function to generate
}
You can't. Your function a() needs to know the last dimension, which is the length of each row in the matrix. You need to pass this as an extra parameter to your function.
void a(int * matrix, int rows, int columns) {
int row = ...
int column = ...
if (row < rows && column < columns) {
cout << matrix[row*columns + column];
}
}
int main() {
...
a(&s[0][0], 10);
...
#include<iostream>
using namespace std;
int number(int (&a)[10])
{
int n= sizeof(a)/sizeof(a[0]);
return n;
}
int main()
{
int n;
cout << " Enter the number of elements ";
cin >> n;
int a[10];
cout << "Enter array elements : ";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<" The number of elements according to main is "<< sizeof(a)/sizeof(a[0])<<endl;
cout<<" The number of elements in the function number is " << number(a);
}
In the above code in the main function "number(a)" Here what exactly are we passing and what is taken by the method. and how does the code work in the function.and what is happening if we are not using "&" symbol in the number function.
My understanding is we are passing a pointer to the first element into the function but I dont know properly.
When you call number(a), you are passing a reference to the array of 10 ints.
Let's take a simpler function.
void foo(int& ref) { }
You can call it with
int i = 20;
foo(i);
Here, a reference to the variable i passed to the function. You can access the value of the variable i in foo through ref. Any changes you make to ref in foo will be visible in the calling function.
Similarly, your function takes a reference to a variable whose type is "an array of 10 ints". The only thing the function does with the reference is compute the number of elements of the array.
It uses a bit of redundant logic. You can simplify that function to:
int number(int (&a)[10])
{
return 10;
}
The function is limited in what it can work with. It is not going to work if you have an array of type float or if you have an array of 20 elements. You can create a template function to make it more general.
template <typename T, size_t N>
size_t number(T (&arr)[N])
{
return N;
}
The above function will work with arrays of different object types and sizes.
I was studying LISTs and playing with function, this program gives 10 number and each time if the entered number is the bigger than the maximum value in our list, that number will be added to our list and finally after 10 tries all members will show up. The program works fine, but what I don't understand is why do I need use "&" in the line 6: " void insertMax(list &lst, int n) {"??
#include <iostream>
#include <list>
using namespace std;
void insertMax(list<int> &lst, int n) {
lst.sort();
int max = lst.back();
if (n > max) {
lst.push_back(n);
}
}
void disply(list<int> lst) {
list<int>::iterator iter = lst.begin();
while (iter!=lst.end()){
cout << *iter << endl;
iter++;
}
}
int main()
{
list<int> numbers;
numbers.push_back(0);
int input=0;
for (int j = 1; j < 11; j++){
cout << "Enter a number: " << endl;
cin >> input;
insertMax(numbers, input);
}
cout << "Now that's all: " << endl;
disply(numbers);
return 0;
}
Thanks in advance.
So you pass a reference to the list rather than a copy of it.
Google "pass by reference" and "pass by value".
Pass by reference means you don't have to make a copy of the whole data structure you are passing (which could be slow - especially if you have a big list)
Having said that, you're question is not quite clear: "Why is & needed during calling this list?" - Line 6 is not a call, it's the declaration of the function signature. So it's saying "When you call me I expect you to pass a reference to a list of ints"
By putting the ampersand (&) in, you specify that the list be taken as a reference, instead of being copied into the function scope. By taking it as a reference you can manipulate the external object.
http://www.cprogramming.com/tutorial/references.html
If I have understood correctly the line 6 is the starting line of the function definition
void insertMax(list<int> &lst, int n) {
lst.sort();
int max = lst.back();
if (n > max) {
lst.push_back(n);
}
}
Symbol & in the first parameter declaration means that the parameter will be a refence to the original argument. So any changes of the list in the function impact on the original argument.
If to remove this symbol & as for example
void insertMax(list<int> lst, int n) {
//...
the it will mean that the function will deal with a copy of the original argument. In this case any changes of the parameter that is pf the copy of the argument will not impact the original argument.
So the new item will be added to a copy of the list but the list itself will not be changed. It is its copy that will be changed.
If you don't add the '&' (pass by reference), any changes you make to the List inside the InsertMax function will not impact the list in your main method.
This is the reason why you'll sometimes see C++ method signatures declared as
void DoSomething(const std::string &value)
{
/*Method Body*/
}
This is done so all that data in the value string is not copied to a new place in memory. If the DoSomething method needs to modify the value string, it will need to make a copy of it first inside of the function. The const modifier makes sure that the reference is read-only by the method.
For example:
std::string DoSomething(const std::string &value)
{
std:string result = value + "some other data";
return result;
}