I was trying out something simple like this:
template<class T>
array insertionSort(array<T> arr) {
for (int index = 1; index < arr.size(); index++) {
for (int insertion = index; insertion > 0 && array[insertion - 1] > array[insertion]; insertion--) {
std::swap(array[insertion - 1], array[insertion]);
}
}
return arr;
}
void main() {
array<int, 10> mine = { 1, 0, 2, 9, 3, 8, 4, 7, 5, 6 };
array result = insertionSort<int>(mine);
cin.get();
}
It seems as though array requires two type parameters (the type
as well as the size
), so how do I pass it to and from a function without knowing the size up front?
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun().
C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.
In order to pass an array as call by value, we have to wrap the array inside a structure and have to assign the values to that array using an object of that structure. This will help us create a new copy of the array that we are passing as an argument to a function.
Passing std::array to functionvoid printArray(const std::array<int, 5> &n) - const is used here to prevent the compiler from making a copy of the array and this enhances the performance. The passed array will be n in this function as &n is the parameter of the function 'printArray'.
In general, you don't really want to pass containers around! The same algorithm which works for std::array<T, N>
also works for other data structures, e.g., std::vector<T>
or std::deque<T>
. The C++ approach in that case is to pass iterator and to [slightly] adjust the algorithm:
template<typename BidrectionalIterator>
void insertionSort(BidirectionalIterator begin, BidirectionalIterator end) {
for (BidirectionalIterator it(begin); it != end; ++it) {
for (BidirectionalIterator insertion(it), tmp(insertion);
begin != insertion && *--tmp > *insertion; --insertion) {
std::swap(*tmp, *insertion);
}
}
}
(I didn't verify that the algorithm actually works but you get the idea).
Note that the algorithm deliberately sorts the sequence in-place! If you want to create a sorted copy, create the copy and sort that: this way you have the choice to do it in-place or not rather than being forced to use an approach which may require excessive memory (OK, when the sequence is large you surely don't want to use this algorithm but that's a separate question).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With