Implementing B=f(A), with B and A arrays and B already defined

前端 未结 4 1391
忘掉有多难
忘掉有多难 2020-12-21 15:54

Suppose I have an array B that has been already defined and used somewhere in a C++ code. Now, suppose that I have another array A that has been de

4条回答
  •  失恋的感觉
    2020-12-21 16:06

    The easiest way it to use std::vector or std::array

    example:

    vector f(const vector& a) {
       return a;
    }
    
    b = f(a);
    

    Actually, you don't have to use one of this classes to store, you may use your own class, that have operator =

    YourClass& operator = (const vector&/* there will be returned value of f, it may be std::array, std::vector or your own class.*/ v) {
        //fill it here.
        return *this;
    }
    

    You may also provide move constructor for it to avoid unnecessary copying.

    for example

    class Array {
        int* data;   
        YourClass& operator = (YourClass&& v) {
            swap(v.data, data);
        }
    }
    
    YourClass f(const YourClass& a) {
       //
    }
    
    Array a,b;
    b = f(a);
    

提交回复
热议问题