Lanyard
Lanyard

Reputation: 11

How do I create an object with a default value if none is passed in the parameter?

I'm trying to create a table that will default to size 500 if no value is passed to the constructor.

Example

Table object; //sets table size to 500 by default
Table object(10000); //sets table size to 10000

This is how I currently have my header set up:

Class Table{
public:
    Table();
    //other functions excluded
private:
    static const int tableSize = 500;
    std::vector<int> A[tableSize];
}; 

How can I do this?

Upvotes: 0

Views: 100

Answers (2)

WhozCraig
WhozCraig

Reputation: 66204

This is likely what you're looking for, assuming you wanted a table and not just a sequence. You code made no mention of the size of each row in that table, so I'm going with what you had:

class Table
{
public:
    Table(size_t n = tableSize) : A(n) {};

    //other functions excluded
private:
    static const size_t tableSize = 500;
    std::vector< std::vector<int> > A;
};

If that size of your row buffers is fixed (say 100 columns), you could use a std::array<> for your row buffers, and thus this instead:

class Table
{
public:
    Table(size_t n = tableSize) : A(n) {};

    //other functions excluded
private:
    static const size_t tableSize = 500;
    std::vector< std::array<int,100> > A;
};

EDIT: Growing Your Hash Table

it appears from comment this is to provide a hash table implementation, and in so doing the need to expand the hash table is required (probably one reason for this in the first place). In that, you can expand the original directly by doing this in conjunction with the first snippet:

void Table::expand()
{
    size_t new_size = 2*A.size() + 1;
    std::vector< std::vector<int>> tmp(new_size);
    for (auto& x : A)
    {
        std::hash<int> hfn;
        for (auto y : x)
            tmp[hfn(y) % new_size].push_back(y);
    }
    std::swap(A,tmp);
}

or something similar. Your hash function would obviously need proper integration as well as potentially taking an optional size factor, etc, but you can hopefully get the idea.

Upvotes: 2

Brian Cain
Brian Cain

Reputation: 14619

You can do it like so:

Class Table{
public:
    Table(int size = 500): A(size) { }
private:
    std::vector<int> A;
};

(note that it's shown this way for brevity. You could/should separate the interface from its implementation and define Table::Table in a source file, and the initializer list should go with it.)

Upvotes: 1

Related Questions