I am writing a Little Man computer simulation and i want to overload the Indexing operator []. I have create a class called LMC and have done the following:
#include <iostream>
using namespace std;
class LMC
{
public:
LMC();
void display();
int& operator[](int index);
~LMC();
private:
int **array;
};
LMC::LMC()
{
array = new int*[100];
for(int i = 0; i < 100; i++)
{
array[i] = new int[3];
}
return array;
}
void LMC::display()
{
for(int i = 0; i < 100;i++)
{
for(int j = 0; j <3;j++)
{
array[i][j] = 0;
array[i][2] = i;
cout << array[i][j]<<" ";
}
cout << endl;
}
}
int& LMC::operator[](int index)
{
return array[index][2];
}
LMC::~LMC()
{
for(int i =0; i < 100 ; i++)
{
delete [] array[i];
}
delete [] array;
array = NULL;
}
int main()
{
LMC littleman;
while(true)
{
int mailbox;
int function;
cout << "What is Mailbox number?" << endl;
cin >> Mailbox;
cout << "What is the function you want to use?" <<endl;
cin >> finction;
//the function is numbers eg 444 and 698;
littleman.display();
littleman[Mailbox] = function;
}
return 0;
}
I can run the program with no error. When i state that mailbox = 0 and function = 123 the is no problem.
This is displayed:
0 0 0
1 0 0
2 0 0
3 0 0
//continuing to 99
This display is wrong. The following must be displayed:
0 0 123
1 0 0
2 0 0
//continuing to 99
Do i have a logical error or am i overriding the array to display the original and how can i fix it?
Your code has a number of errors which will not let it compile namely:
in the LMC() constructor, you have return array;. Constructors never return anything (they don't even have the return type), so you can not use return in them.
after void LMC::display(), you have a ;, which is an error, because this is not a definition, but implementation. You should omit it and just leave void LMC::display() { <...> }
void LMC::display() is missing the closing } in the end, right before the operator[].
in main() you have typos in Mailbox (capital M in one case, and normal m in another. In C+++ Mailbox and mailbox are different variables) and finction instead of function.
As for your problem, you are rewriting the values of the aray in display() function:
array[i][j] = 0;
array[i][2] = i;
That's why you don't see any results.
These lines
array[i][j] = 0;
array[i][2] = i;
in LMC::display() destroy the contents of the array you're trying to display.
Furthermore, there's an extra semicolon at the end of void LMC::display();, so your code is not supposed to compile.
Related
really new to C++, trying to instantiate some basic algorithms with it. Having trouble returning the correct result for selection sort. Here is my code
#include <iostream>
#include <array>
#include <vector>
using namespace std;
// Selection Sort :
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
return m;
}
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void selectionSort(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); ++i)
{
int min = findMin(arr, i);
swap(arr[i], arr[min]); // Assume a correct swap function
}
}
}
void print(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << "";
cout << endl;
}
}
}
int main()
{
vector<int> sort;
sort.push_back(2);
sort.push_back(1);
sort.push_back(7);
sort.push_back(4);
sort.push_back(5);
sort.push_back(3);
print(sort);
cout << "this was unsorted array";
cout << endl;
cout << findMin(sort, 0);
cout << "this was minimum";
cout << endl;
selectionSort(sort);
print(sort);
}
I am getting the following results:
comparison_sort.cpp:20:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
}
^
1 warning generated.
2
1
7
4
5
3
this was unsorted array
1
this was minimum
1
2
4
5
3
0
My question is: What is causing this control path error? Why is the "7" here being replaced with a "0"?
Thanks in advance! Sorry for the noob question.
I have reviewed all my current functions and nothing seems to explain why the 7 is replaced with a 0. I have tried multiple integers and it looks like the maximum number is always replaced.
The warning is very real, and it alludes to the problem that's breaking your sort as well.
You are currently returning m inside your loop body. What that means is that if the loop is entered, then the function will return m on the very first time around the loop. It only has a chance to check the first element.
And of course, if a is the last index of the array, then the loop will never execute, and you will never explicitly return a value. This is the "control path" which does not return a value.
It's quite clear that you've accidentally put return m; in the wrong place, and even though you have good code indentation, some inexplicable force is preventing you from seeing this. To fix both the warning and the sorting issue, move return m; outside the loop:
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
}
return m;
}
I need help with this code.
What I want is to make a parametric constructor and initialise/set the value of array in it.
Question: Make a class with arrays of integers and initialise it in a constructor. Then find the smallest and largest numbers using functions.
But I am stuck at how to initialise the array in the constructor.
I want to take data input in both ways
(1) By user, using cin
(2) By giving my own values
class Numbers
{
int Arr[3];
public:
Numbers() //default constructor
{
for (int i=0 ; i<=2 ; i++)
{
Arr[i]=0;
}
}
Numbers(int arr[]) //parameteric constructor
{
for (int i=0;i<=2;i++)
{
Arr[i]=arr[i];
}
}
};
int main()
{
int aro[3] = {0,10,5};
Numbers obj (aro);
return ;
}
The solution is pretty simple. I've made a new program from start again (for sake of understanding). According to your requirement, you wants to get input of array elements from the user dynamically and assign them to a constructor and use a method to print the highest value.
Consider the following code:
#include <iostream>
using namespace std;
const int N = 100;
class Numbers
{
int largest = 0;
public:
Numbers(int, int[]);
void showHighest(void)
{
cout << largest << endl;
}
};
Numbers::Numbers(int size, int arr[])
{
for (int i = 0; i < size; i++)
{
if (arr[i] > largest)
{
largest = arr[i];
}
}
}
int main(void)
{
int arrays[N], total;
cout << "How many elements? (starts from zero) ";
cin >> total;
for (int i = 0; i < total; i++)
{
cout << "Element " << i << ": ";
cin >> arrays[i];
}
Numbers n(total, arrays);
n.showHighest();
return 0;
}
Output
How many elements? (starts from zero) 3
Element 0: 12
Element 1: 16
Element 2: 11
16
Note: I've initialized a constant number of maximum elements, you can modify it. No vectors, etc. required to achieve so. You can either use your own values by removing the total and its followed statements and use only int arrays[<num>] = {...} instead. You're done!
Enjoy coding!
I suggest to use std::vector<int> or std::array<int>.
If you want initialize with custom values you can do std::vector<int> m_vec {0, 1, 2};
Thank you so much for your help. I was basically confused about how to use arrays in a constructor and use setters/getters for arrays in a class. But you all helped a lot. Thanks again.
Numbers(int arr[])
{
for (int i=0;i<=9;i++)
{
Arr[i]=arr[i];
}
Largest=Arr[0];
Smallest=Arr[0];
}
void Largest_Number()
{
header_top("Largest Number");
Largest=Arr[0]; //Using this so we make largest value as index zero
for (int i=0 ; i<=9 ; i++)
{
if(Arr[i]>Largest)
{
setLargest( Arr[i] );
}
}
cout<<"Largest Number: "<<getLargest()<<endl;
}
I have a class named mvector which has two private variables, num (denotes number of elements in the array), and an integer pointer to store the array address.
mvector has 2 public functions, get() and print() to get the elements of the array, and print them (respectively).
However, when I try to print the values, some values are correct, while others are garbage values.
#include<iostream>
using namespace std;
class mvector
{
private:
int num;
int *ele;
public:
void get();
void print();
};
void mvector::get()
{
cin>>num;
int data[num];
for(int i=0; i<num; i++)
{
cin>>data[i];
}
ele=data;
}
void mvector::print()
{
for(int i=0; i<num; i++)
{
cout<<*ele<<endl;
ele++;
}
}
int main()
{
mvector v1;
v1.get();
v1.print();
}
Input: 5 1 2 3 4 5
Expected Output: 1 2 3 4 5
Actual Output: 1 1 1877615960 4 5
The program does not make a great sense.
For example the variable length arrays is not standard C++ feature. So the declaration of the array
cin>>num;
int data[num];
is not correct.
Within the function get the data member ele is assigned with the address of the first element of a local array that will not be alive after exiting the member function. So using this pointer in the member function print invokes undefined behavior.
You have to define the array dynamically.
Moreover within the function print the pointer ele is incremented and loses its initial value. It means that you could call the function the second time
You should define a class with constructors and destructor.
More or less working code can look the following way.
#include <iostream>
class mvector
{
private:
size_t num = 0;
int *ele = nullptr;
public:
void get();
void print() const;
};
void mvector::get()
{
size_t n;
std::cin >> n;
if ( n != num )
{
delete [] ele;
ele = nullptr;
if ( n != 0 )
{
ele = new int[n];
}
num = n;
}
if ( num != 0 )
{
for ( size_t i = 0; i < num; i++)
{
std::cin >> ele[i];
}
}
}
void mvector::print() const
{
int *p = ele;
for ( size_t i = 0; i < num; i++ )
{
std::cout << *p << ' ';
++p;
}
std::cout << '\n';
}
int main()
{
mvector v1;
v1.get();
v1.print();
v1.get();
}
For the input like this
5
1 2 3 4 5
0
The output will be
1 2 3 4 5
and the allocated memory will be freed.
The line
ele=data;
is the source of your problems.
data is a local array, a non-standard VLA, but it is still a local array. When the function returns data is destructed and ele points to an object that is no longer valid. Accessing ele after the function returns is cause for undefined behavior. The garbage values you are seeing is just one symptom of undefined behavior.
You can change that function to use:
void mvector::get()
{
cin>>num;
ele = new int[num];
for(int i=0; i<num; i++)
{
cin>>ele[i];
}
}
That will solve your immediate problem. However, there are other issues you have to contend with when managing memory yourself. See http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three for additional details.
I am having a run-time error in this program, it has no syntax error but crashes when it is run. i am using dev-c++ 4.9.9.2. I tried to find the error but i couldn't find it. If anyone can help then please find the errors and correct me.
#include<iostream.h>
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
main()
{
DisplayVUID();
char a[20] = "mc123456789";
DisplayReverse(a, 20 );
StoreDiagonal();
system("pause");
}
void DisplayVUID()
{
int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
for(i=0;i<20;i++)
{
cout<<name[i];
}
cout<<endl;
}
void DisplayReverse(char a[], int arraysize)
{
int i;
cout<<"MY VU id in Reverse is ";
for(i=arraysize-1;i>=0;i--)
{
cout<<a[i];
}
cout<<endl;
}
void StoreDiagonal()
{
int a[9][9] ;
int i;
int row, col;
for (i = 0; i<9;i++)
{
for(i=0;i<9;i++)
{
a[row][col] = 0;
}
}
a[1][1] = 1;
a[2][2] = 3;
a[3][3] = 0;
a[4][4] = 2;
a[5][5] = 0;
a[6][6] = 2;
a[7][7] = 3;
a[8][8] = 9;
a[9][9] = 8;
for(i = 0 ; i < 9 ; i ++)
{
for( i = 0 ; i < 9 ; i ++)
{
cout<<a[row][col];
}
}
}
Things don't work this way on Stackoverflow, from next time onward try hard to do things on your own, do your research and then come here.There seemed to be many errors in your program but I tried to remove some bugs and finally, It works on my system. I have also recommended some nice things via comments that you can look in the program:
EDIT: I noticed that some undefined string because of unassigned spaces in the array was printed out in the reverse function but i have corrected it now.
#include<iostream>
#include<stdlib.h>
using namespace std;// use namespace otherwise cout won't work
void DisplayVUID();
void DisplayReverse(char[], int);
void StoreDiagonal();
int main()// In C++ always declare a main function like this,its good habit
{
int i=0;
DisplayVUID();
char a[20] = "mc123456789";
while(a[i]!='\0')
i++;// Did this to ensure that cout will print only up to the null character,earlier it was printing some undefined characters along with the data in the array.
DisplayReverse(a, i );
StoreDiagonal();
system("pause");
return 0;//return 0
}
void DisplayVUID()
{
//int i;
char name[20] = "mc123456789";
cout<<"My VU id is ";
//for(i=0;i<20;i++)// no need for this loop at least here
//{
cout<<name;
//}
cout<<endl;
}
void DisplayReverse(char a[], int i)
{
cout<<"MY VU id in Reverse is ";
// for(i=arraysize-1;i>=0;i--)
//{
while(i--)
cout<<a[i];//instead of the for loop traversing for the whole arraysize i have made it go up to only the null terminator this way it doesn't print undefined characters.
//}
cout<<endl;
}
void StoreDiagonal()// i don't understand by the way what this function is here for , its not an error though.
{
int a[9][9] ;
int i,j,c=1;
//int row, col;// you didn't initialize row and column and placed it inside the loop
for (i = 0; i<9;i++)
{
for(j=0;j<9;j++)
{
a[i][j] = 0;
if(i==j)
{
a[i][j]=c;//instead of manually assigning do it like this.
c++;
}
}
}
for(i = 0 ; i < 9 ; i ++)
{
for( j = 0 ; j < 9 ; j ++)
{
cout<<a[i][j];// the elements of the array don't display like a table , this is not an error but to make your output readable do it by your self
}
}
}
a[9][9]=8;
remove this line, you will be fine. Array indexing starts from 0 not 1.
Also I would like to point that in your function DisplayVUID() change i<20 to a[i]!='\0' because the values after '\0' will be garbage values.
I'm new to C++, this is my first week since the upgrade from fortran. Sorry if this is a simple question, but could someone help me with operator overloading. I have written a program which has two classes. One object contains a vector and two scalars, the other class simply contains the first object. In a test implementation of this code I suspect the operator overloading to be at fault. The program tries to accomplish the following goals:
1) Initialize first structure.
2) Initialize a second structure containing the initialized first structure. After this is imported, the value val0 = 10 is added to every element of the vector in the enclosing structure, structure2.structure1 .
3) Output structure1 and structure2 variables to compare.
For this simple program my output is:
100
100
0
0
0 0 10
1 1 11
2 2 12
3 3 13
...
I was expecting:
100
100
0
10
0 0 10
1 1 11
2 2 12
3 3 13
...
Clearly my overloaded = operator is copying my vector properly, but one of the scalars? Could someone help?
#include <iostream>
using namespace std;
typedef double* doublevec;
// This first class contains a vector, a scalar N representing the size of the vector, and another scalar used for intializing the vector.
typedef class Structure1
{
int N, vec0;
doublevec vec;
public:
// Constructor and copy constructor.
Structure1(int Nin, int vecin) : N(Nin), vec0(vecin) { vec = new double [N]; for(int i = 0; i < N; i++) { vec[i] = i + vec0; } }
Structure1(const Structure1& structurein);
// Accessor functions:
int get_vec0() { return vec0; }
int get_N() { return N; }
doublevec get_vec() { return vec; }
// Overide equivalence operator:
Structure1& operator=(const Structure1& right)
{
//Handle Self-Assignment
if (this == &right) return *this;
N = right.N;
vec0 = right.vec0;
for (int i = 0; i < N; i++)
{
vec[i] = right.vec[i];
}
return *this;
}
// Destructor:
~Structure1() { delete []vec; }
} Structure1;
Structure1::Structure1(const Structure1& structurein)
{
N = structurein.N;
vec = new double[N];
for(int i = 0; i < N; i++)
{
vec[i] = structurein.vec[i];
}
}
// This class just contains the first structure.
typedef class Structure2
{
Structure1 structure;
// Mutator Function:
void mutate_structure();
public:
// Constructor:
Structure2(const Structure1& structurein) : structure(structurein) { mutate_structure(); }
// Accessor Function:
Structure1 get_structure() { return structure; }
// Destructor:
~Structure2() {}
} Structure2;
void Structure2::mutate_structure()
{
int N = structure.get_N();
Structure1 tempstruct(N,10);
structure = tempstruct;
}
int main (int argc, char * const argv[])
{
const int N = 100;
Structure1 structure1(N,0);
Structure2 structure2(structure1);
cout << structure1.get_N() << endl;
cout << structure2.get_structure().get_N() << endl;
cout << structure1.get_vec0() << endl;
cout << structure2.get_structure().get_vec0() << endl;
for(int i = 0; i < N; i++)
{
cout << i << " " << structure1.get_vec()[i] << " " << structure2.get_structure().get_vec()[i] << endl;
}
return 0;
}
it looks like vec0 isn't initialized by your copy constructor...
Try modifying your copy constructor to:
Structure1::Structure1(const Structure1& structurein)
{
N = structurein.N;
vec = new double[N];
for (int i = 0; i < N; i++)
{
vec[i] = structurein.vec[i];
}
// ADD THIS LINE
vec0 = structurein.vec0;
}
Your copy-constructor Structure1::Structure1(const Structure1 &) doesn't copy vec0. It's not getting initialised at all, so gets whatever is in memory.
Also, you might want to check Structure1's operator=. If you assign a large vector to a small vector, then you'll potentially overflow the array in the destination. You might need to reallocate memory in operator=.