如何在使用此数组初始化对象时知道数组的大小

how to know the size of the array while initializing an object using this array?

本文关键字:数组 对象 初始化      更新时间:2023-10-16

问题说:定义一个动作对象的容器(可能是模板)(将被命名为Runner)。操作对象 (AO) 是执行用户提供的功能的对象。这个想法是,一旦操作容器加载了AO,就可以要求它运行或执行它们。执行结果在 Results 数组中返回。例:

 AO a1(mul, x, x); //if run method is called it returns x*x
 AO a2(add, y, 1); //if run method is called it returns y+1
 AO a3(print, s); //if run method is called it prints s on cout
 Runner<AO> r = {a1,a2,a3};

所以现在在 runner 类中,我应该如何实现一个接受常量数组并知道它大小的构造函数

 template<typename a>
 class runner{
 a* m;
 int size;
public:
runner(const a x[]){
//how to know the size of x[] to initialize m=new a[size] and then fill it with a1,a2,a3 ??
}
数组

无法知道它的大小,因此您应该将其作为参数传递给构造函数。
更简单:使用 std::vector .使用方便std::initializer_list您可以使用大括号初始值设定项{}继续初始化对象。这里有一个例子:

#include <iostream>
#include <vector>
#include <initializer_list>
template<typename a>
class runner{
private:
    std::vector<a> objects;
public:
    runner(std::initializer_list<a> init) {
         objects.insert(objects.end(), init.begin(), init.end());
    }
    void iterate() {
        for(auto obj : objects)
            std::cout << obj << std::endl;
    }
};
int main() {
    //As template type I've chosen int, you can choose your own class AO aswell
    //This calls the constructor with the std::initializer_list
    runner<int> test = {1,2,3,4,7,0};
    test.iterate();
    return 0;
}

您可以做的是推送向量中的所有对象,然后将其传递给 Ctor。

请按照以下步骤操作:

包括:

#include<vector>

在主():声明类 AO 的对象并将它们推送到vector<AO> x

AO a1(mul, x, x); //if run method is called it returns x*x
AO a2(add, y, 1); //if run method is called it returns y+1
AO a3(print, s);
vector<AO> x;
x.push_back(a1);
x.push_back(a2);
x.push_back(a3);
Runner<AO> r(x);

修改模板类

class Runner{
    a* m;
    int size;
public:
    Runner(vector<a> x)
    {
        m = new a[x.size()];
        for (int i = 0; i < x.size(); i++)
        {
            m[i] = x.at(i);
        }
    }
};

希望这真的是你想要的