c dante
c dante

Reputation: 11

using size() to return the number of elements currently in my class (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:

  1. A pointer to int that will point to a dynamically allocated array which holds the values currently in in IntSet

  2. An Int that holds the current size of the array (it will need to be updated whenever the add() method because of array resize

  3. 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?

Upvotes: 1

Views: 295

Answers (3)

Mohamad Elghawi
Mohamad Elghawi

Reputation: 2124

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.

Upvotes: 0

Viet
Viet

Reputation: 583

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

Upvotes: 0

Ethan Fine
Ethan Fine

Reputation: 529

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

Upvotes: 1

Related Questions