2

I am creating a function titled linspase with C++17 with the following input structure linspace(double upper, double lower, int size). The function should create size evenly spaced numbers between lower and upper. Programming this function is easy; however, I want it to create an std::array<double, size> where the function will determine the array size from the function call and pass back the data type std::array<double, size>. I know templates are the only way to do this, but I am not sure how to build the template. In a general pseudo code I think it looks something like this.

template <typedef T, size_t size>
T linspace(double lower, double upper, int num)
{
    /* ... Function meat goes here to create arr of size 
           num of evenly space numbers between lower and upper
    */     
    return arr
}

However, I know this template declaration is not right and I am not sure what it is supposed to look like. To be clear, I want it to return an std:;array of a specific size, not an std::vector.

Jon
  • 1,621
  • 5
  • 23
  • 46

1 Answers1

4

If you (correctly) pass the array size as a template parameter, you don't need it as one of the function arguments, so:

template <size_t size>
auto linspace(double lower, double upper) -> std::array<int, size>
{
    std::array<int, size> arr{};
    //populate the array ...
    return arr;
}

Since you're using c++14, you can get rid of the return value altogether, and have a prototype like:

template <size_t size>
auto linspace(double lower, double upper)

Then you can use it like this:

auto arr = linspace<1>(0, 1);

for(auto a : arr)
{
    std::cout << a << std::endl;
}
Barry
  • 286,269
  • 29
  • 621
  • 977
p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
  • This is a great solution, thank you. Unfortunately I just realized there is no `push_back()` function for `std::array` that will allow me to populate an array one element at a time. As a result, it looks like I will need to use `std::vector` instead. I was hoping to use array to keep the arrays down to the minimum size, but it does not look like that will be possible. – Jon May 09 '19 at 01:55
  • @Jon You could use an iterator for similar behaviour – Tharwen May 09 '19 at 08:47
  • @Tharwen, can you give an example of how that is done. I can see examples of how an iterator can be used to display the existing contents of an array, but I do not know how to use it to populate an std::array one value at a time, up to the max amount. – Jon May 09 '19 at 13:33
  • Declare the iterator first with `auto it = arr.begin()`, then instead of `push_back(value)` you can write `*it = value; it++`. The main difference is that it's possible go past the end of the array and crash the program but since you already know how many elements you're inserting that shouldn't be a problem – Tharwen May 09 '19 at 15:25