如果参数中未传递任何值,如何创建具有默认值的对象

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

本文关键字:创建 对象 默认值 何创建 参数 任何值 如果      更新时间:2023-10-16

我正在尝试创建一个表,如果没有值传递给构造函数,该表的默认大小将为500。

示例

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

这就是我目前设置标题的方式:

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

我该怎么做?

这很可能是您想要的,假设您想要一个,而不仅仅是一个序列。您的代码没有提到该表中每个的大小,所以我使用您的代码:

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;
};

如果行缓冲区的大小是固定的(比如说100列),则可以使用std::array<>作为行缓冲区,因此:

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:增加哈希表

从注释中可以看出,这是为了提供一个哈希表实现,在这样做的过程中,需要扩展哈希表(这可能是最初的原因之一)。在这种情况下,您可以通过与第一个片段结合使用来直接扩展原始代码:

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);
}

或者类似的东西。您的散列函数显然需要适当的集成,并且可能需要一个可选的大小因子等,但您有望得到这个想法。

你可以这样做:

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

(请注意,为了简洁起见,它是这样显示的。您可以/应该将接口与其实现分离,并在源文件中定义Table::Table,初始化器列表也应该随之而来。)