简体   繁体   English

在C ++中选择运行时数组或向量

[英]Choose at runtime array or vector in C++

I have a problem described as below :: 我有如下问题:

    class datad {
    private:
        int *a;
        int _size;
        vector<int> v;

    public:
        datad(int arr[], int size) {
            _size = size;
            for (int i = 0; i < size; i++)
                a[i] = arr[i];
        }
        datad(vector<int> ve)
        {
            v = ve;
            _size = ve.size();
        }

        void printdata()
        {
             // print data which the object has been initialized with
             // if object is initialized with vector then print vector
             // array print array
        }
    };

   int main()
   {
        // print only vector data
    int a[] = { 9,4,8,3,1,6,5 };
    datad d(v1);
    d.printdata();

    // print only array data

    datad d1(a, 7);
    d1.printdata();
 }

I need to find the way the object is initialized and then based on the same should be able to printdata accrodingly. 我需要找到对象初始化的方式,然后基于该对象应该能够强制打印数据。 Can someone help me understand if it is possible at all? 有人可以帮我了解一下是否有可能吗?

Add a bool usesVector to your class and set it to true or false in each constructor as appropriate. 在您的类中添加一个bool usesVector ,并在每个适当的构造函数中将其设置为truefalse Then, in printdata , simply check the value of the boolean. 然后,在printdata ,只需检查布尔值。

Or you can set size to -1 in the vector case (as it's otherwise unused) and just check for that. 或者,您可以在向量情况下将size设置为-1 (否则将不使用),然后进行检查。

By the way, your array implementation is broken, because you never allocate any memory for it. 顺便说一下,您的数组实现被破坏了,因为您从未为其分配任何内存。 You'd be much better off using only the vector version. 你会关闭使用矢量版本要好很多 You can still initialise that vector from array data if you wish. 如果愿意,您仍然可以从数组数据中初始化该向量。

You can set a flag in respective constructor and check that flag during the printing method. 您可以在各自的构造函数中设置一个标志,并在打印方法期间检查该标志。

I hope this is for learning purposes, otherwise as noted you maybe better of using just the vector version. 我希望这是出于学习目的,否则如前所述,您最好只使用矢量版本。 When using dynamic memory management in class you need to be aware of things like rule of three and I guess there is also rule of five. 当使用类动态内存管理,你需要知道的东西一样的规则3 ,我想也有五个规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM