using size() to return the number of elements currently in my class (c++) - c++

I'm currently writing this program and i have no idea how to use the size() method to return the number of values.
I have to create a class called IntSet, which represents a mathematical Set of Integers using the following data members:
A pointer to int that will point to a dynamically allocated array
which holds the values currently in in IntSet
An Int that holds the current size of the array (it will need
to be updated whenever the add() method because of array resize
An Int which holds the number of values currently in the
IntSet (it will need to be updated in the add() and remove()
methods
So far I've created a constructor and destructor and after doing the other methods I'm completely stumped on this one.
Header:
class IntSet
{
public:
IntSet(); //Constructor
~IntSet(); //Destructor
int size();
bool isEmpty();
bool contains();
void add(double number);
void remove(double number);
private:
int* ptr; //pointer to the array
int sizeOfArray; //current size of the array
int currentValue; //number of values currently in IntSet
}
and the main code so far:
#include <iostream>
#include "IntSet.hpp"
IntSet::IntSet()
{
sizeOfArray = 10;
currentValue = 0;
int* ptr = new int[10];
}
IntSet::~IntSet()
{
delete ptr;
}
So how would I even begin to use the size() method here?

if currentValue is indeed the number of values in the intSet as your comment claims, than size() can simply return currentValue.

Size is the number of element in your set.
At first, you should init it with value 0
Every you add new element successful, increase current size by 1
Every you remove element successful, decrease current size by 1
Method size(), you only need return current size of your set

From the specification you have given, currentValue holds the number of values in your set so you would define the following in your .cpp file.
int IntSet::size() const
{
return currentValue;
}
Keep in mind that you will need to increment/decrement this value whenever you add/remove an element to/from your set.

Related

Constructing an array of class attribute in a different class C++

I have to do a project where one class Row has an array of integers int* OneArray and then another class Array has an array of the first class Row* TwoDArray. In essence the class has a 2D array on integers, and I can easily do the construction of the 2D array when it is in one class. However, now I am completely stumped.
The construction of the Row is simple enough:
//set length of array
numOfRows = intRows;
//Create space for array
OneArray = new int[intRows];
//populate array with random numbers
for(int i=0; i<intRows; i++)
{
OneArray[i] = GenerateRandom(9,0);
}
This is where I am stuck (Construction of Array):
//Set Number of Cols
NumOfCol = intCols;
//create length for each row
int intLength = 4;
for(int i=0; i<NumOfCol; i++)
{
//create space and call row constructor with length
TwoDArray = new Row(intLength);
//increase length for jagged array
intLength++;
}
As it is now it writes over the current array after each for loop (which is expected). So, I need to index TwoDArray like TwoDArray[i], but as soon as I try to do that then I get this error:
"invalid user-defined conversion from 'Row*' to 'const Row&'."
Note: If I take the line out of the for loop only the first array is made and not until intCol. intLength is increasing because I technically need a jagged array which has got different sizes in each array.
My classes look like this:
class Row
{
public:
//Constructors
Row();
Row(int intRows);
Row(const Row& objPrev);
//Accessors
int getNumOfRows();
int getRowArray(int intRow);
//Mutators
void setRowArray(int intRow, int intChange);
//Destructor
~Row();
private:
int* OneArray;
int numOfRows;
}
and
class Array
{
public:
//Constructors
Array();
Array(int intRows, int intCols);
Array(const Array& objPrev);
//Accessors
int getNumOfCol();
Row getTwoDArray(int intCol, int intRow);
//Mutators
void setTwoDArray(int intCol, int intRow, int intChageTo);
//Destructor
~Array();
private:
Row* TwoDArray;
int NumOfCol;
}
Any Help or suggestions are appreciated.
With your loop in Array you allocate a single Row object multiple times, overwriting the pointer in each loop. That leads to a memory leak as only the last will be available through the variable TwoDArray. Also, at the end of the loop all you will have is an "array" of only a single element, the last allocated Row object.
The problem is that you can't do the array allocation using new[] at the same time as you call a specific constructor. You can not do e.g.
TwoDArray = new Row[NumOfCol](intLength);
Instead you have to split the allocation and initialization into two parts:
TwoDArray = new Row[NumOfCol]; // Allocates memory, default constructed Row objects
for (int i = 0; i < NumOfCol; ++i)
{
TwoDArray[i] = Row(intLength); // Initialize each element
}
This of course requires you follow the rules of three or five (or zero) for the copying in the loop to work.

How do I manage to create a vector class in c++?

I was introduced to pointers, I quite get it. but I don't know how to store variables in the vector class using pointers.
Here is what I got from my understanding but how should I complete it?
class Vector{
int size;
int* element;
public:
vector(int x);
int size() const { return size }
};
first, you need to define a value that stores the current size - (number of elements inside the vector) - to be able to add values at the end of the vector.
int curr_vec_size;
also, the actual size of the vector should be saved in a variable to check every time you add a value that allocated memory is not full
int memory_size;
second, you need to allocate memory dynamically by using "new" in the constructor
vector(int size)
{
element = new int[size]; //allocating memory (array of integers)
memory_size= size; //size of allocated memory
curr_vec_size= 0; //no values in the vector
}
then you can make a method that takes an int value and adds it to the dynamic array.
void add_value(int passed_val)
{
if(curr_vec_size < memory_size)
{
element[curr_vec_size]=passed_val; //adding the value in the vector
curr_vec_size ++; //because you have added a new value
}
else
cout<<"vector is full \n";
}
Finally, don't forget to delete the memory you've allocated by using destructors that deletes the pointer to this allocated memory.
vector()
{
delete[] element;
}
To complete what you started, you simply need to use new[] operator to allocate memory to store your int values:
vector(int x)
{
size = x;
element = new int[size]; // this allocates an array of int with a size of "size"
}
Then, you can use element[i] to access i's element of your array.
You'll later need (it's a must) to release allocatd memory to prevent memory leak by implementing a destructor:
~vector()
{
delete [] element;
}
Note that you should (must) also also follow at least the rule of 3 to have you vector be copiable.

C++ Add to the end of array

I created a pointer to pointer to a dynamic vector, is called "list".
listaFiguras::listaFiguras(){
numElements = 0;
list = new figuraGeom* [numElements];
}
Here is my class too:
class listaFiguras {
//Atributos
int numElements;
figuraGeom **list;
public :
//Constructor sin parametros
listaFiguras();
//Destructor
~listaFiguras();
//Sets y Gets
void setnumElementos(int);
virtual void setLista(figuraGeom**);
int getnumElementos();
virtual figuraGeom* getLista();
//Vaciar lista
void vaciarLista();
//AƱadir elemento
void anyadirElemento(figuraGeom *);
};
Now I have to create a method called anyadirElemento but do not understand how I can do this:
Take as a parameter a pointer to figuraGeom, and added at the end of the dynamic array pointed to by list.
I got this:
void listaFiguras :: anyadirElemento (figuraGeom * parameter) {
}
Any help will be appreciated, Thanks!
It would be simpler if instead of the dynamically allocated array you would use std::vector<figuraGeom *>
You have to keep the current position in the array that to know where to add a new value. For example let assume that you defined such data member of the class
int position;
and initialized it to zero some way (for example in a constructor of the class)
Then the function could look the following way provided that the array may not be reallocated
void listaFiguras :: anyadirElemento (figuraGeom * parameter)
{
if ( position < numElements ) list[position++] = parameter;
}
So I would define data members of the class as
class listaFiguras {
//Atributos
int numElements;
int position;
figuraGeom **list;
//...
If you are allowed to enlarge the initially allocated array then the function should reallocate it each time if position is equal to numElements where numElements also will be changed or you should keep another variable that will store the current size of the array.
A very simple dynamic array is define as follow:
array size
pointer to array
You need to know how many elements are currently in the array to be able to use them; and when adding/removing an element you simply create another array with one less or one more element (which involves copying the old array into the new).
Note: this is extremely inefficient adding an element is O(N) where N is the number of elements already in the array but it's also very simple, in real code use std::vector<T> which performs addition at the end in amortized O(1).

Segfault in my stack implementation (C++) code, but cannot understand why

To set the record straight, I am fairly new to C++ and most of my experience in programming is in Java. I'm writing an array based stack implementation and I cannot seem to read any of the data saved in my stack.
Objects can be pushed and this seems to function normally. Commenting out the top() operation yields a successful output of zero, which seems to tell me that I know the item is at least being added to the array.
However, reading the item, I get a segfault error. After a quick google or two, I learned that a segfault means that there is an operation accessing data it does not have access to. This leads me to think that my top() function does not have access to the array. It is a private member of the class, but my previous knowledge of OOP tells me that a class method should have access to all private variables.
Could anyone help point me in the right direction here? (Apologies if the documentation is a bit excessive for such a primitive data structure, let me know if it should be removed).
Thanks! Code is below:
#include <iostream>
using namespace std;
/*
Class: arrayStack()
A simple stack implemented with a single array.
Handles char objects.
*/
class arrayStack {
int length; //cap on stack length
int count; //Keeps track of which element in the array to pop from.
char array[]; //Hold data here
public:
/*
arrayStack()
Constructor used to create a stack object. No default constructor exists, the length (l) is a required argument as a parameter to create a stack.
l space is reserved in the array and count is set to -1, the int value required for an empty stack.
*/
arrayStack(int l)
{
char array[l];
length = l;
count = -1;
}
/*
push() -- return type void.
Method to add a desired char element (o) to the stack.
*/
void push(char o)
{
array[count] = o;
count++; //Increment the counter to accurately pull element from array.
}
/*
pop() -- return type char.
Method to remove an element from the stack. Element is pulled from the stack and returned.
*/
char pop()
{
//temp space to store pulled element before returning.
char temp;
temp = array[count];
//Replace popped element with null to reduce memory waste. Then decrement counter for proper functioning of the stack.
array[count] = '\0';
count--;
return temp;
}
/*
top() -- return type char.
Method which returns the top element of the function without deleting it from the stack. Useful for inspection and testing, but functionally very similar to pop().
*/
char top()
{
//temp space to store pulled element.
char temp;
temp = array[count];
return temp;
}
/*
isEmpty() -- return type boolean.
Method which checks the stack for elements. If there are no elements, the method returns true. If there exists one or more elements, the method will return false.
Method is very simple-- a simple check against the count (int) variable.
*/
bool isEmpty()
{
if (count == -1) {
return true;
} else {
return false;
}
}
/*
size() -- return type int.
Method which returns the number of elements in the stack.
*/
int size()
{
return count++;
}
};
int main() {
arrayStack stack(10);
stack.push('c');
cout << stack.top(); //SEGFAULT OCCURS HERE.
cout << stack.isEmpty();
return 0;
}
Your member array is still uninitialized:
arrayStack(int l)
{
char array[l];
length = l;
count = -1;
}
Here, you create a new array (which I doubt is legal anyway, since C++ doesn't support VLA's. It should probably be
arrayStack(int l)
{
array = new char[l];
length = l;
count = -1;
}
You also need to implement a destructor to delete the allocated memory. Which means you also need a copy constructor and copy assignment operator.

While inserting nodes in heap how to use bubble up?

Following is my code which doesnot properly bubbles up the larger value .Can any one help out .The problem is somewhat at count++ .
#include<iostream>
using namespace std;
class heap{
public:
int count;
heap(int c)
{
count=c;
}
int Arr[10];
void insert(int num);
void deletemax();
void print();
};
void heap::insert(int num){
if(count==10){
cout<<"Heap full\n";
exit(1);
}
else{
Arr[count]=num;
count++; //The real problem arises here that the compiler adds 1 to count and when the code moves ahead it sets position var to count++ value and tries to compare a value at Arr[POS] with its parent whereas there is no value at this place set uptill.
}
int POS=count;
while(Arr[POS]>Arr[(POS-1)/2]){
int temp;
temp=Arr[POS];
Arr[(POS-1)/2]=temp;
POS=(POS-1)/2;
}
}
void heap::print(){
for(int i=0; i<10; i++){
cout<<Arr[i]<<endl;
}
}
int main(){
heap h(0);
int a;
int b=0;
while(b<10){
cout<<"Insert node in heap\n";
cin>>a;
h.insert(a);
b++;
}
h.print();
return 0;
}
I would agree, that's where your problem is.
There are many issues with the code you posted, some of which include:
As to your specific issue, I would guess you need to change the line in heap::insert() to "int POS=count-1;" to properly start iterating from the back of the array.
You need to consider the case of adding an element to an empty array and what then happens in your sorting code.
Your constructor allows someone to create a heap that will overflow the fixed sized array, for example heap(1000). In addition, the Arr member is not initialized which means it has undefined data for any value but heap(0). In this case your constructor should not take any parameters and count should just be initialized to 0.
The purpose of the code is confusing. Is it a heap, a sorted array, an attempt to approximate a heap with an array, none of the above? If you are simply trying to implement a fixed sized sorted array then I believe your sorting code in insert() will not work (e.g., consider adding 100 to a heap containing [1,2,3]).
There are other, more basic things, wrong (like not using any the STL containers, public class member, non-const parameter passing, "using std", etc...) but I'm assuming you are merely experimenting/playing here.