简体   繁体   中英

One-dimensional and multidimensional arrays in function parameters

I'm experimenting a bit with one-dimensional and multidimensional arrays in C++ and passing them to functions as parameters.

template <typename T, std::size_t SIZE_ROW>
void printArray(std::array<T,SIZE_ROW> &arr)
{
    for (auto const &r : arr)
      cout << r << " ";
    cout << endl;
}

template <typename T, std::size_t SIZE_ROW, std::size_t SIZE_COL>
void printArray(std::array< array<T ,SIZE_COL>,SIZE_ROW>&arr)
{
      for (auto const &r : arr)
      {
        for (auto const &c : r)
        {
          cout << c << " ";
        }
        cout << endl;
      }
}

Can someone explain why the commented line doesn't work? I'm a bit confused, since it seems that I need to pass the size of the array rows/cols to the function as well as the array itself, but the variant without passing the size does work and the other doesn't.

array<double,12> monthlyTemperature = {};
    
printArray(monthlyTemperature);
// printArray(monthlyTemperature, monthlyTemperature.size());

Thanks

As said in the comments, when instantiating a function template, the template arguments can either be specified explicitly or deduced through template argument deduction .

std::array<double, 12> myArray = {};

printArray<double, 12>(myArray);  // Explicit
printArray(myArray);              // Deduced from myArray's type

You can also 'pass' some parameters with the above syntax while deducing others, for instance in this function that only prints out the first few elements of the array:

template <std::size_t FirstElements, typename T, std::size_t SIZE_ROW>
void printPartialArray(const std::array<T, SIZE_ROW>& arr) 
{
    constexpr std::size_t Size = std::min(FirstElements, SIZE_ROW);
    for (size_t i = 0; i < Size; ++i) {
        std::cout << arr[i] << " ";
    }
}

std::array<double, 12> myArray;
printPartialArray<5>(myArray);   // T and ROW_SIZE are deduced

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