【问题标题】:Initialize a vector in a class?在一个类中初始化一个向量?
【发布时间】:2020-01-20 18:31:17
【问题描述】:

从上一个问题中我了解到我可以通过这种方式初始化 2D 向量:

vector<vector<double>> Example(3); 

代替:

vector<vector<double>> Example={{},{},{}}

在这种情况下,我将在示例中提供三个“行”,对吗?

现在我想在一个类中进行初始化:

    class Perceptron(){
     int NumbersOfRowsThatIwant;
     vector<vector<double>> Example(NumbersOfRowsThatIwant);
    };

现在行数只在构造函数中定义:

Perceptron::Perceptron(int x)
{
  NumberOfRowsThatIwant=x;
}

但这可能是错误的,我该如何解决?

【问题讨论】:

标签: c++ class vector constructor initialization


【解决方案1】:

你的意思好像是下面这个

#include <iostream>
#include <vector>

class Perceptron
{
public: 
    Perceptron( size_t n ) : Example( n ) {}

private:
    std::vector<std::vector<double>> Example;
};

int main() 
{
    Perceptron p( 3 );

    return 0;
}

数据成员int NumbersOfRowsThatIwant; 是多余的,因为您总是可以获得像Examp;le.size() 这样的“行”数。例如

#include <iostream>
#include <vector>

class Perceptron
{
public: 
    using size_type = std::vector<std::vector<double>>::size_type;

    Perceptron( size_type n ) : Example( n ) {}

    size_type row_number() const { return Example.size( ); }
private:
    std::vector<std::vector<double>> Example;
};

int main() 
{
    Perceptron p( 3 );

    auto n = p.row_number();

    std::cout << n << '\n';

    return 0;
}

程序输出是

3

如果您想使用具有预定义“行”数的默认构造函数,您可以定义类,例如

#include <iostream>
#include <vector>

class Perceptron
{
public: 
    using size_type = std::vector<std::vector<double>>::size_type;
    Perceptron() = default;
    Perceptron( size_type n ) : Example( n ) {}

    size_type row_number() const { return Example.size( ); }
private:
    static const size_type DEFAULT_NUMBER = 3;
    std::vector<std::vector<double>> Example { DEFAULT_NUMBER };
};

int main() 
{
    Perceptron p( 3 );

    auto n = p.row_number();

    std::cout << n << '\n';

    Perceptron p2;

    n = p2.row_number();

    std::cout << n << '\n';

    return 0;
}

【讨论】:

    【解决方案2】:

    您可以为此使用成员初始化器列表:

    class Perceptron {
      private:
         int NumbersOfRowsThatIwant;
         vector<vector<double>> Example;
      public:
        Perceptron(int x);
    };
    
    Perceptron::Perceptron(int x): NumberOfRowsThatIwant(x),
                                   Example(NumbersOfRowsThatIwant)
    { }
    

    但请记住,初始化顺序仅取决于成员的声明顺序,而不取决于成员初始化器列表中的顺序。

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2021-12-28
      • 2014-03-01
      • 1970-01-01
      • 2022-06-11
      相关资源
      最近更新 更多