简体   繁体   中英

How can I make an array a parameter of a function in C++?

I have a function in a program I am writing for my school science fair, and what it needs to do is take in an array as a parameter, encrypt the values of the array, and store the encrypted values in a string. How can I do this?

There are several ways to do this. Here are few examples:

  • C-style

     void f(T *array, size_t size); 

    In this style, the array decay to the pointer to the first argument which gets passed to the function as first argument. Since this conversion loses the size of the array, you've to pass the size as well, which I do as second argument to the function. Use this as:

     T array[N]; //N is some compile-time constant. f(array, N); 
  • C++-style

     template<typename T, size_t size> void f(T (&array)[size]); void f(std::vector<T> & array); 

    In this style, you can pass the array by reference, which retains the size of the array, or you can use std::vector<T> instead. Use this as:

     T array[N]; f(array); //calls the first version (the template version) std::vector<T> v; //fill v f(v); //calls the vector version 

    Added by @Mike: or you can use this, which is even better:

     template<typename FwdIterator> void f(FwdIterator begin, FwdIterator end) { for( ; begin != end ; ++begin) { //your code } } 

    This is better and more generic, because with it, you can use standard containers (such as std::vector , std::list , etc) as well as normal arrays. For example,

     T array[N]; std::vector<T> v; //fill v f(array, array+N); //okay f(v.begin(), v.end()); //also okay. 

    Cool, isn't it?

void YourFunction(const int myarray[]);

Otherwise if you want accept any type

void YourFunction(const void* myGenericArray);

Hope this helps

void encrypt(Array& array, /*other parameters*/)

would do, whatever array type you use.

If your array is a C-style pointer, you can also just pass it:

void encrypt(int* array, /*other parameters*/)

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