简体   繁体   中英

How to pass a vector by copy, and by reference, to a function?

    int main () {
       vector <int> vectorF;
       functionX <vector<int>&, long> (vectorF, 1L);
    }

    template <typename dataTypeA, 
              typename dataTypeB> dataTypeB functionX (dataTypeA argA, 
                                                       dataTypeB argB)
    {   
    }

This code changes the actual values in the vector, if modified in the function definition.

What is the way to pass the vector by copy?

Simply call the function as,

functionX (vectorF, 1L);  // ok! explicit function calling isn't needed

However, as a side not I would like to mention that making a copy of a whole vector just for a function doesn't make much sense. You can simply change the function definition to,

template <typename dataTypeA, typename dataTypeB>
dataTypeB functionX (const dataTypeA& argA, dataTypeB argB)
{                    ^^^^^^^^^^^^^^^^^ const reference 
}

if you are using this vector for reading purpose.

functionX <vector<int>, long> (vectorF, 1L);

Addind a & after the vector<int> will make the dataTypeA to be a reference to a vector. If you want a copy to a vector, remove the &

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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